0
function Example() {
  const [state, setState] = useState(0)
  
  const someFunction= ()=>{
    ///some task that return a value
    let value = getFunction()
    setState(value)
    console.log(state) //prints 0 ???
  }

  return ( <></> );
}

export default Example;

As you can see the state doesn't change. What can I do to solve this. I tried using useEffect too

I tried using useEffect but no luck

1 Answers1

1

This is from the React documentation:

I’ve updated the state, but logging gives me the old value

function handleClick() {
  console.log(count);  // 0

  setCount(count + 1); // Request a re-render with 1
  console.log(count);  // Still 0!

  setTimeout(() => {
    console.log(count); // Also 0!
  }, 5000);
}

This is because states behaves like a snapshot. Updating state requests another render with the new state value, but does not affect the count JavaScript variable in your already-running event handler.

This is interesting too.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437