Yeah! absolutely correct... and that's why I use two diffrent states
my scenario was
setState(state);// Update some statedoSomething();// Do something with the state
and I was not getting the updated state. as you can see in the example
and two solve the I use useEffect.
setState(state);// Updates the stateuseEffect(()=>{doSomething(state)// do something with the updated state.},[state])// This will call again when the state is updated
I realized my comment was already included in your post. Sorry about that.
Actually, there is a simple way to write it without useEffect: setState(prev => prev + 1). It will update properly even if you update it multiple times in one render.
constFunc=()=>{const[count,setCount]=useState(0);// initially count = 0 (When it was first mounted)consthandleClick=()=>{setCount(prev=>prev+1);// count = 1 setCount(prev=>prev+1);// count = 2}return(<buttononClick={handleClick}>{count}</button>
)}
It is called functional update. This one is easier to use or understand, and I recommend to use it when needed. reactjs.org/docs/hooks-reference.h...
Yeah! absolutely correct... and that's why I use two diffrent states
my scenario was
and I was not getting the updated state. as you can see in the example
and two solve the I use useEffect.
I realized my comment was already included in your post. Sorry about that.
Actually, there is a simple way to write it without
useEffect
:setState(prev => prev + 1)
. It will update properly even if you update it multiple times in one render.It is called functional update. This one is easier to use or understand, and I recommend to use it when needed.
reactjs.org/docs/hooks-reference.h...
Yeah! I will definitely try it...