How to resolve setState doesn’t update immediately issue? How to access REACT state immediately after state gets updated?
As many times, while working with function components in ReactJs, I faced up an issue of using variable updated state immediately after setState hooks.
It is because setState, and useState does not make changes directly to the state object. … useState create queues for React core to update the state object of a React component. So the process to update React state is asynchronous for performance reasons. That’s why changes don’t feel immediate.
So, here I propose my solution to what you can do in a very simple and basic manner. You do not have to do much, just follow up any of the solutions and get onto your desired result.
SOLUTION 1: Here is the first solution you can try and resolve the above-mentioned issue.
- Create a function that is nothing other than a middleware, write in your logic code you want to perform with an updated state.
- Call that above-created function right after the setState hook, or wherever you want to use after state update.
function demo(){
// here you write you logic with updated state variable
} ;
function yourFunc() {
setState(state_var_name) ;
demo();
}
SOLUTION 2: Here is the second alternative by which you can also resolve the above issue.
- Create a useEffect hook and in its callback function write up the logic code you want to perform with an updated state.
- (Optional) Pass the state variable in the useEffect hook’s second parameter which is none other than an Array.
useEffect(() => {
// write up your logic here
}, [state_var_name] );
function yourFunc() {
setState(state_var_name) ;
}
With any of the above solutions, you can resolve this issue and can work smoothly on your builds.