Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

reactjs - React sometimes rerenders between two setStates, depending on setState order

I've got two simple useStates.

At one point, they're set, one after another. This happens within a useEffect with [] deps.

      canvas.toBlob(blob => {
        if (blob) {
          setBounds([width, height]);
          setUrl(URL.createObjectURL(blob));
        } else console.log("no blob");
      });

The above code (first set bounds, then url) causes the component to rerender once, with both states set properly.

However, the code below (first url, then bounds):

      canvas.toBlob(blob => {
        if (blob) {
          setUrl(URL.createObjectURL(blob));
          setBounds([width, height]);
        } else console.log("no blob");
      });

makes the component rerender twice. The first render has only the url set, then only on the second render, the bounds are set as well.

Why does changing the order of these two lines change the rerenders?

question from:https://stackoverflow.com/questions/65874530/react-sometimes-rerenders-between-two-setstates-depending-on-setstate-order

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think the reason is because you're inside a callback function, React isn't batching updates.

So the order of these states being set actually matters and somehow setting the url before the bounds is triggering an additional render which I cannot make out from the given code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...