When you use useState
, don't assume that the state will be updated immediately. React batches state updates and triggers a re-render after the component has been rendered. The updated state will be visible only after the component re-renders, which typically happens after the function inside useEffect
.
In other words, state updates are asynchronous
, and the new state value won't be immediately available right after calling setState. You need to rely on the component's next render cycle to access the updated state.
check this one setstate-in-reactjs-async-instead-of-sync