Search code examples
reactjsreact-hooksuse-state

Why useState is not updating immediately after button click?


I am trying to update State on click of a button, but when I am doing a console.log it is showing me the old value. Although it was updating the state as I saw in the components tab (react dev tools).

Here is my code.

const App=()=>{
const [test,setTest]=useState(false);

 const fun=()=>{
    setTest(true);
    console.log(test); 
   }
return(
   <>
    <button onClick={fun}>Test</button>
   </>
}

When I click the first time, my output is false. But when I click the second time, my output is true. I want true as output in my first click itself.


Solution

  • In react, updating state is asynchronous. Updated value is only available during the next render. Meaning, updating & them immediately console logging will give you the old state.

    setTest(true);
    console.log(test); //test is still false
    

    You can print the state value to see the update -

    return(
       <>
        <button onClick={fun}>Test</button>
        {test}
       </>
    }