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)
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
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With