2
function Test() {
  const [state, setState] = React.useState(0);

  const handler = () => {
    setState(1);
    console.log(state);
  }

  return (
    <div>
      <div>My state: {state}</div>
      <button onClick={handler}>Click</button>
    </div>
  );
}

I know that React.useState is asynchronous, but i don't fully undestand how it works. In my example in handler function I need to console.log new state (1) after setState(1), but it's logging 0. How can I fix it?

Alex
  • 33
  • 4

2 Answers2

2

setState isn't asynchronous, but the value will only be updated when a new render is triggered (to batch multiple updates).

function Test() {
  const [state, setState] = React.useState(0);

  const handler = () => {
    setState(1);
  }

  console.log(state);

  return (
    <div>
      <div>My state: {state}</div>
      <button onClick={handler}>Click</button>
    </div>
  );
}

This way you will see the new value logged. There is no way to get the updated value inside the handler even with useCallback.

matthiasgiger
  • 1,086
  • 9
  • 17
1

you need to use an callback function, so that it will update accordingly. In react functional component you can achieve this by useEffect hook.

 useEffect(()=>{
      console.log(state);
    },[state])

Now it will render the component, whenever the state changes

karthik
  • 528
  • 4
  • 19