4

In functional components, we use useState as opposed to this.setState for classComponents. But as far as I know, you can only set one state at a time with useState, while setState lets you set multiple states at a time, (e.g. this.setState({a1: true, a2: false})).

Does this mean if you wanted to set two states simultaneously with useState, you'd get a double re-render, which is ineffficient? Is there a way to get around this?

Qrow Saki
  • 932
  • 8
  • 19

1 Answers1

7

AFAIK that's right but you can also think that in most cases you just group states in the way they are correlated instead of having a big this.state with bunch of properties without being related with each other, that also sucks in some way

So commonly you won't be updating two states every time and if you do that, most probably you want to mix those states into one.

So supposing you have these two states:

const [state1, setState1] = useState(...);
const [state2, setState2] = useState(...);

And you always in your onChange function (or whatever) do:

const onChange = () => {
  setState1(...);
  setState2(...);
}

You should mix those into one state like this:

const [state, setState] = useState({ state1: ..., state: ...}); // or it could be other thing than an object...
Agustin Moles
  • 1,364
  • 7
  • 15