React State Does Not Update Immediately - Use Useeffect To Work With The New Value

TopicSource
๐Ÿงฉ ReactTop 6 React Hook Mistakes Beginners Make - YouTube

If you want to work with a state variable after it is updated, use useEffect.

If you want to do something after a state variable changes, you can't do immediately afterwards. useState happens asynchronous, so you can't use the updated value in the next line.

Instead, you need to use useEffect to wait for the re-render.

You can pass in a dependency into the useEffect to tell React, what state variables it should watch.

useEffect(() => {
	console.log(count);
}, [count]); // <-- this is an array of dependencies for useEffect

  1. Use the function version of react hooks if your new state depends on the previous state