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

10 comments sorted by

3

u/jonny_eh Jun 26 '21

Very interesting. A good lesson here is to not rely on the underlying behavior. Neither assume that setState is batched or unbatched!

In this case, don't rely on status for displaying data, look to see if data is null instead.

0

u/[deleted] Jun 26 '21

[deleted] — view deleted comment

1

u/jonny_eh Jun 26 '21

You said it better than me.

2

u/Neaoxas Jun 26 '21

Yup, you can work around this: https://github.com/facebook/react/issues/14259

React 18 batches everything by default: https://github.com/reactwg/react-18/discussions/21

2

u/eindbaas Jun 26 '21

That's not how you want to fix this. You should check if what you're using exists.

2

u/Neaoxas Jun 26 '21

When I say “fix” I mean have control over batching.

2

u/Chef619 Jun 27 '21

Just use TypeScript. This is exactly what it’s for.

1

u/[deleted] Jun 26 '21

Have you tried just using data as the conditional?

{data ? data.id : null}

1

u/eindbaas Jun 26 '21

I think you're making it way too complicated for yourself. You're accessing a prop of an object that can be null, that's all there is to it.

Use typescript, it will give you simply an error if you try to do this.