Search code examples
javascriptreactjssettimeoutuse-effect

React setTimeout and setState inside useEffect


I have this code and my question is why inside my answer function I get the initialState. How to set the state in a proper way to get the right one inside a callback of setTimeout function?

const App = () => {
  const [state, setState] = useState({
    name: "",
    password: "",
  });

  useEffect(() => {
    setState({ ...state, password: "hello" });
    setTimeout(answer, 1000);
  }, []);

  const answer = () => {
    console.log(state);
    // we get initial State
  };
  return <div className="App"></div>;
};

Solution

  • The reason is closure.

    answer function will always log that value of state which setTimeout() function closed over when it was called.

    In your code, since setTimeout() function is called when state contains an object with empty values, answer function logs that value, instead of logging the updated value.

    To log the latest value of state, you can use useRef() hook. This hook returns an object which contains a property named current and the value of this property is the argument passed to useRef().

    function App() {
      const [state, setState] = React.useState({
        name: "",
        password: "",
      });
    
      const stateRef = React.useRef(state);
    
      React.useEffect(() => {
        stateRef.current = { ...stateRef.current, password: 'hello'};
        setState(stateRef.current);
        setTimeout(answer, 1000);
      }, []);
    
      const answer = () => {
        console.log(stateRef.current);
      };
      return <div></div>;
    }
    
    ReactDOM.render(<App/>, document.getElementById('root'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
    <div id="root"></div>