Why React Hook Value Is Not Updated In Async Function?
Solution 1:
setState runs asynchronously so it is not immediately reflected in the function code block. You can try using useEffect to watch changes of your state.
useEffect(() => console.log('value', value), [value])
Solution 2:
In your case const [value, setValue] = useState('old');
setValue is nothing but same like setState in class Components. So since setState and setValue is asynchronous functions, you can never predict when the values will get updated.
So either you can use componentDidUpdate
in class components or useEffect
like useEffect(() => callFn();, [value])
. so here callFn()
is afunction which will be called after value has been updated.
hope it helps. feel free for doubts
Solution 3:
Ok, here is what I think is happenning: You click the button, which calls your run function - then the run function calls setState.
- I think setState is supposed to cause a rerender of the component with the new value which would be shown immediately if you were displaying it somewhere. So if you want to see immediate changes, add a display.
- When you console log in the run function immediately after setState, the component has not been rerendered which means you are still looking at the old value.
- When the component rerenders, you are not seeing the console logged value because the run function has not been called again. Clicking the button twice should console log the new value because by then the component has rerendered with that new value.
Post a Comment for "Why React Hook Value Is Not Updated In Async Function?"