How to prevent inline functions from binding to old state values

后端 未结 2 522
梦毁少年i
梦毁少年i 2021-01-20 03:27

In a project with React components using hooks, I am trying to understand how to properly avoid calling callbacks that are bound to old state values. The below example illus

2条回答
  •  孤街浪徒
    2021-01-20 03:50

    You should useCallback and pass it as a dependency to your effect.

    const doStuff = useCallback(() => {
      console.log(message);
    }, [message]);
    
    useEffect(() => {
      const interval = setInterval(doStuff, 1000);
      return () => clearInterval(interval); // clean up
    }, [doStuff]);
    
    

    Here when message gets updated it will have its new value in the doStuff

提交回复
热议问题