0
const [button, setButton] = React.useState("off")

React.useEffect(()=>{
       setButton("on");
       console.log(button)
    },[])
const onClickHandler = ()=>{
       setButton("off");
}

Lets take this code as an example, every time i reload the page, I expect the button to console log "on" since i did setButton("on") but it console logs "off" but when I click on that button it should setButton("off") but now it prints out 'on'. so its like its one step behind. why is it happening. and when should i use useEffect. Sorry about my english.

  • TL;DR React state updates are asynchronous and are processed between render cycles. Console logging state *right after* enqueueing an update logs state from the *current* render cycle, ***not*** the state for the *next* render cycle. – Drew Reese Jan 09 '21 at 07:31
  • So whats the solution? – Vivekanand Mogali Jan 09 '21 at 07:32
  • Solution for what? You asked why the log was a step behind. If you simply want to log a state update then use a separate `useEffect` hook with the state value as a dependency. – Drew Reese Jan 09 '21 at 07:33
  • i mean what if i want to use that "on" state right after reloading. what should i do? – Vivekanand Mogali Jan 09 '21 at 07:34
  • You could make your initial state "on" if you want that value when the component mounts. If you really have a different question for something you are really trying to do then I suggest you edit your question to reflect that and vote to re-open. – Drew Reese Jan 09 '21 at 07:35
  • And my problem is not just about useState. even while using functions calling in context, same thing is happening – Vivekanand Mogali Jan 09 '21 at 07:35

0 Answers0