最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to call multiple setter functions of useState react hook without re-render? - Stack Overflow

programmeradmin0浏览0评论

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)

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)

Share Improve this question edited Oct 29, 2022 at 20:28 SayJeyHi asked Mar 12, 2019 at 20:19 SayJeyHiSayJeyHi 1,8414 gold badges25 silver badges48 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 17

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.

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

发布评论

评论列表(0)

  1. 暂无评论