In my react project, using useState hook's setState is not changing my state value, after calling setState.
const [name, setName] = useState("Old");
useEffect(()=>{
setName("New");
console.log(name); //Always prints "Old"
})
I tried adding a callback to setName, but it wouldn't accept that too.
I finally used the useEffect hook
Since setState is asynchronous, it was not updating the state immediately on call, it rather initiates the process of changing the state and javascript proceeds to execute to the lines below.
So I ended up using useEffect hook to execute anything that I wanted to run after the state name is changed, adding the state name as a dependency as shown below.
const [name, setName] = useState("Old");
useEffect(()=>{
setName("New");
})
useEffect(()=>{
console.log(name); // This Always gets the new value
}, [name])