How to call multi setter useState react hooks

This is a great question because it challenges the best practice of having a setState for each slice of state.

The best way is to create a POJO with two keys (to be explicit), one for running, one for jumping. Then, the setter will have 3 permutations.

  • setting just jumping
  • setting just running
  • setting both
const [actions, setActions] = useState({running: false, jumping: false});
const { jumping, running } = actions;

I don't think this is a best practice, you should split them up whenever you can to avoid this pattern. However, this is one instance where it may be worth merging them to save a render (which can be desirable).


You can just call them sequentially like this (demo):

const Comp = ({ flag }) => {
  const [running, setRunning] = useState(false);
  const [jumping, setJumping] = useState(false);

  const setBoth = () => {
    setRunning(true);
    setJumping(true);
  };

  return (
    <>
      {"running: " + running}
      {"jumping: " + jumping}
      <button onClick={() => setBoth()}>setboth</button>
    </>
  );
};

Alternatively, you can set them both at the same time like this:

const Comp = ({ flag }) => {
  const [RJ, setRJ] = useState([false, false]);

  const setBoth = () => {
    setRJ([true, true]);
  };

  return (
    <>
      {"running: " + RJ[0]}
      {"jumping: " + RJ[1]}
      <button onClick={() => setBoth()}>setboth</button>
    </>
  );
};

https://codesandbox.io/s/0pwnm2z94w