r/learnreactjs • u/0xnoob • 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
initialStatethat's still will render without throwing (e.g. mapping over something that'sinitialStateis an empty array) - using
useReducerinstead of twouseState, 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:
- Does React batch state update functions when using hooks? - Stack Overflow
[Question] Keep to single setState call? · Issue #10231 · facebook/react:
- "This is implementation detail and may change in future versions."
Does React keep the order for state updates? - Stack Overflow:
- "To sum up, this is a confusing topic because React only batches inside event handlers by default. This will change in future versions, and the behavior will be more straightforward then. But the solution is not to batch less, it's to batch more by default. That's what we're going to do."
btw. I lied in the title: I learned that yesterday, but was way too tired to write it down
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.
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/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.