Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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().

functionApp() {
  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);
  }, []);

  constanswer = () => {
    console.log(stateRef.current);
  };
  return<div></div>;
}

ReactDOM.render(<App/>, document.getElementById('root'));
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script><divid="root"></div>

Solution 2:

The function answer is a closure other the value of state, it captures the value of a variable inside of it's scope when it's defined. When the callback inside of useEffect is called, the answer method it's got is closed over the value of the state before your setState.

That's the function with whom you'll be calling setTimeout so even if there's a timeout, the old value of the state will be delay.

Post a Comment for "React Settimeout And Setstate Inside Useeffect"