Thomas Segato
Thomas Segato

Reputation: 5223

When does hooks update in react?

When does a hook update when using a setter? I can see it somehow must be async. Consider following sample it shows, that the hook does not update instantly. Do you await hooks (if yes how) if you need the value just after, or what is normal approach here?

https://codesandbox.io/s/romantic-snyder-dv84c?fontsize=14&hidenavigation=1&theme=dark

Upvotes: 0

Views: 59

Answers (2)

Molly
Molly

Reputation: 1907

The function to update the state are called asynchronously, thus the updated state won't get reflected immediately.

You can instead do the action when the state changes, and for that we have useEffect hook.

import React, { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  const [index, setIndex] = useState(0);

  function increment() {
    setIndex(prevState => prevState + 1);
  }
  useEffect(() => {
    alert(index);
  }, [index]);

  return (
    <div className="App">
      <div>{index}</div>
      <button onClick={() => increment()}>Increment</button>
    </div>
  );
}

I have updated your codesandbox here

Upvotes: 2

Cameron Downer
Cameron Downer

Reputation: 2038

Because the setIndex call is asynchronous, you cannot use it in the alert call and expect the updated value.

Instead I would use the useEffect hook for any actions that depend on the new state value.

useEffect(() => {
  alert(index);
}, [index])

function increment() {
  setIndex(prevIndex => prevIndex + 1); // update based on previous value
}

Upvotes: 0

Related Questions