Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call multi setter useState react hooks

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)

like image 232
SayJeyHi Avatar asked Mar 12 '19 20:03

SayJeyHi


2 Answers

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

like image 164
jsdeveloper Avatar answered Nov 01 '22 10:11

jsdeveloper


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

like image 31
Nicholas Gentile Avatar answered Sep 27 '22 03:09

Nicholas Gentile