最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React useRef current not updating every time - Stack Overflow

programmeradmin3浏览0评论

I have a ponent that uses the useRef hook on a div in order to calculate the height whenever a ponent is removed from that div.

The problem I am having is that the clientHeight is not always updating when I remove an element from the div. It does work if I use useState and a useEffect. Is there any reason why the following method won't work? How can I get this to work without using more state and another useEffect?

Doesnt work:

useEffect(() => {
    dispatch(setAppNotificationHeight(notificationRef.current?.clientHeight));
  }, [notificationRef.current?.clientHeight]);

Works:

  const [height, setHeight] = useState<number | undefined>(undefined);

  useEffect(() => {
    setHeight(notificationRef.current?.clientHeight);
  });

  useEffect(() => {
    dispatch(setAppNotificationHeight(height));
  }, [height]);

I have a ponent that uses the useRef hook on a div in order to calculate the height whenever a ponent is removed from that div.

The problem I am having is that the clientHeight is not always updating when I remove an element from the div. It does work if I use useState and a useEffect. Is there any reason why the following method won't work? How can I get this to work without using more state and another useEffect?

Doesnt work:

useEffect(() => {
    dispatch(setAppNotificationHeight(notificationRef.current?.clientHeight));
  }, [notificationRef.current?.clientHeight]);

Works:

  const [height, setHeight] = useState<number | undefined>(undefined);

  useEffect(() => {
    setHeight(notificationRef.current?.clientHeight);
  });

  useEffect(() => {
    dispatch(setAppNotificationHeight(height));
  }, [height]);

Share Improve this question edited Sep 23, 2022 at 21:37 Chris G 2,1102 gold badges10 silver badges22 bronze badges asked Sep 23, 2022 at 21:34 SeanSean 1,4663 gold badges11 silver badges30 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

I think your issue is discussed in here. Mutating a reference does not necessarily trigger a rerender, and does not necessarily trigger the useEffect. You could use a useCallback hook instead of your working solution (see code snippet from this answer in particular).

发布评论

评论列表(0)

  1. 暂无评论