0

That's not my actual code, just an mock to explain my issue.

I know the using setState function triggers a new render, but in a piece of code I'm trying to debug that seems to happens instantly, eg:

const [stateA,setStateA] = useState(false);
const [stateB,setStateB] = useState(false);

useEffetc(() => {console.log(stateA, stateB)}, [stateA,stateB]);

//async code, request callback
() =>{
    setStateA(true);
    setStateB(true);
}

// true false
// true true

What I got is that right after setStateA(true); has done, a new render is triggered, that activates the console log with the partial results. After that, the js interpreter resume the execution from setStateB(true);, with a new render.

This of course breaks the component logic, and my React knowledge, as I have always thought the the interpreter never leave a code block in the middle to do something else.

Nemus
  • 1,322
  • 2
  • 23
  • 47
  • 1
    Which version of React are you using? Before React 18, state updates that were triggered asynchronously weren't batched. This is what I think is happening in your code as well. – Yousaf Jul 28 '22 at 09:38
  • @Yousaf React@16.13. Can you explain what do you mean with "weren't batched"? – Nemus Jul 28 '22 at 09:39
  • 1
    If you call state setter functions multiple times like you have, React would batch the update to ensure that only one re-render takes place BUT if multiple state update calls were triggered asynchronously, those state updates were not batched; each state update will cause a re-render. – Yousaf Jul 28 '22 at 09:41
  • 1
    Also see: [React Blog - Automatic Batching in React 18](https://reactjs.org/blog/2022/03/29/react-v18.html#new-feature-automatic-batching) – Yousaf Jul 28 '22 at 09:45
  • All clear, thank you – Nemus Jul 28 '22 at 09:54

0 Answers0