11

I want to call multiple setter functions together when some event has been triggered.

sth like :

const [running, setRunning] = useState(false);
const [jumping, setJumping] = useState(true);

then what should we do, if we want to setRunning and setJumping together? (avoid re-render component)

SayJeyHi
  • 1,559
  • 4
  • 19
  • 39

2 Answers2

15

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

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

  const setBoth = (_e) => {
    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 = (_e) => {
    setRJ([true, true]);
  };

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

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

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
jsdeveloper
  • 3,945
  • 1
  • 15
  • 14
0

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).

Nicholas Gentile
  • 1,512
  • 1
  • 9
  • 16
  • Claiming it will render multiple time is False. "React batches state updates that occur in event handlers and lifecycle methods. Thus, if you update state multiple times in a
    handler, React will wait for event handling to finish before re-rendering." https://stackoverflow.com/questions/33613728/what-happens-when-using-this-setstate-multiple-times-in-react-component
    – Pascal Oct 29 '22 at 23:55