Why is my state not getting updated - Hooks version

Posted on October 18, 2019

Probably because you are using it wrong.

Find class based version here

const [value, setValue] = useState('');
function handleChange(newValue) {

Why is your state not getting updated?

Straight out of React docs, setState may be asynchronous. What does that mean?

Let’s find out.

setTimeout(() => console.log('foo'), 0);

What is the output?

First the second console.log fires and then the first one inside the setTimeout function. This happens because setTimeout is asynchronous and is moved to the browser thread. So the code that runs after setTimeout gets executed however small the timeout is.

Same is the case with setState Because of it’s asynchronous state, the statement after is being called before the actual setState function.

How do we fix this?

React calls the functional component once again whenever the state is updated. Hence, to see the updated state, just look in the render.

1function App() {
2 const [value, setValue] = useState("");
3 function handleChange(newValue) {
4 setValue(newValue);
5 }
6 console.log(value);
7 ...

But in real world react components, there would be multiple states (and props) and this would trigger the console.log every time any one of these is updated. Instead, a more effective approach would be:

1function App() {
2 const [value, setValue] = useState("");
3 useEffect(() => {
4 console.log(value);
5 }, [value]);
6 function handleChange(newValue) {
7 setValue(newValue);
8 }
9 ...

Note that the useEffect has the required state as dependency and thus would run whenever it is changed.

Buy me a coffeeBuy me a coffee