0

I have multipe hook.

const [A, setA] = useState([]);
const [B, setB] = useState([]);
    
useEffect(() => {
  setA(["foo"]);
  setB(["bar"]);
}, []);
    
useEffect(() => console.log(A), [A])
useEffect(() => console.log(B), [B])

A update is reflected immediately and B is not. If I flip the order, the result is also flipped (B is reflected immediately).

How do I make those two updates to happen together?

Edit: I use useEffect to check my state.

fstanis
  • 5,234
  • 1
  • 23
  • 42
Roki Elf
  • 1
  • 2

2 Answers2

0

On React 17 this is the default behavior, you get 1 render per state change.

Starting React 18 state changes might be batched together, but if you want to be sure they always get changed together you need 1 state variable, not two.

Evert
  • 93,428
  • 18
  • 118
  • 189
  • can you please share any link referencing to this? because what you said isn't clear to me – Meet Bhalodiya Aug 03 '22 at 04:14
  • @MeetBhalodiya here's a reference from the blog: https://reactjs.org/blog/2022/03/29/react-v18.html#new-feature-automatic-batching lmk if this is still confusing – Evert Aug 03 '22 at 04:43
-1

This question was already asked in Stackoverflow once.

Like @Evert mentioned, if the multiple states are closely related, then it's better to batch them together. Each state updates causes a component re-render, and as of I think it can't be changed in any way.

So group your states together so that you update the whole group itself, causing only one state update per batch state update.

const [aAndb, setAAndB] = useReducer(
  (state, newState) => ({...state, ...newState}),
  {A: "foo", B: "bar"}
)

setAAndB({A: "Bar"});

And here's the other similar question that I mentioned

Jishnu Raj
  • 170
  • 3
  • 16