How to deal with useState delay

Viewed 8571

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 :)

3 Answers

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])

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

Check it out

Related