r/learnreactjs • • Jun 26 '21

TIL: state updates aren't always batched together - only in event handlers

I had this weird problem, that after I successfully fetched and called setState for the status- and the data-values, rendering them would throw an error, because data was still undefined:

function SomeComponent({ url }) {
  const [status, setStatus] = React.useState("idle");
  const [data, setData] = React.useState(null);

  React.useEffect(() => {
    if (!url) return;

    fetch(url).then((data) => {
      setStatus("success");
      setData(data);
    });
  }, [url]);

  return <div>{status === "success" ? data.id : null}</div>;
}

the code is stripped down to only contain the necessary stuff

This will throw an TypeError: Cannot read property 'id' of null .

It took me a long time to realize that those two setState calls aren't batched together, instead it will render the component right after setStatus("success"); and before calling setData(data); in the very next line, thus data is still null!

This isn't the first time I called setState somewhere that wasn't a event handler: I have done fetching data several times before, but I must have always done something unintentionally to prevent this:

  • calling them in the right order by coincidence

  • checking implicitly if the value exists in my JSX (e.g. via nullish coalescing (??) or optional chaining (?.))

  • by having an initialState that's still will render without throwing (e.g. mapping over something that's initialState is an empty array)

  • using useReducer instead of two useState, because those two values are interconnected (which is the right solution, imho)

I'm obviously not the first one who found this out, but I hope that I could find at least one person who wasn't aware of this and can keep him from falling into the same trap as me!

Here are some interesting links I found on this topic:

btw. I lied in the title: I learned that yesterday, but was way too tired to write it down

17 Upvotes

Duplicates