VicHofs
VicHofs

Reputation: 311

How to deal with useState delay

In React, I often use the states of constants in other operations following setState() (or api interactions), but it’s common for the state to not be updated yet when that section of the code runs, most of the time resulting in errors/unexpected behavior.

Is there a best practice for dealing with this? Or a recommended alternative to useState itself?

Thanks :)

Upvotes: 7

Views: 20568

Answers (3)

Marik Ishtar
Marik Ishtar

Reputation: 3049

You can use useEffect to execute a function after the state has changed, but this method will fire the what's inside the useEffect first render as well, and to fix that you need to create a custom hook

const [age, setAge] = useState(0)

useEffect(() => {
   console.log('the age has changed', age)
}, [age])

Upvotes: 9

bakar_dev
bakar_dev

Reputation: 996

Because setState() is asynchronous, mostly errors/unexpected results occur due to this behavior, so you need to understand this asynchronous behavior properly by playing state. If you handle component life cycle properly with the proper state handling then you will not see any unexpected behavior. More info: https://reactjs.org/docs/state-and-lifecycle.html and https://css-tricks.com/understanding-react-setstate/

Upvotes: 0

acbay
acbay

Reputation: 892

Without hooks react setState gets a callback function, but with hooks you should use useEffect for doing it.

Check it out

Upvotes: 0

Related Questions