Lekar123
Lekar123

Reputation: 53

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>;
};

Upvotes: 3

Views: 3555

Answers (2)

Yousaf
Yousaf

Reputation: 29282

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>

Upvotes: 7

Axnyff
Axnyff

Reputation: 9964

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.

Upvotes: 0

Related Questions