iTranslated by AI
Self-Correcting Components: Interpreting the Official Technique of Updating State During Rendering
To maintain high product quality in React, it's important to write code that aligns with React's paradigm. A well-known page in the official documentation, "You Might Not Need an Effect," introduces undesirable uses of useEffect and alternative techniques.
This article focuses on the technique presented in the section "Adjusting some state when a prop changes," which involves updating state during rendering.
At first glance, this technique may seem odd. Many developers know about it but are unsure whether they should actually use it. However, a hallmark of React's official documentation is that even seemingly unusual code turns out to perfectly align with React's design when understood deeply. While it's important to approach official documentation critically rather than blindly trusting it, in React's case, you often find yourself returning to the conclusion that "after much thought, the official docs were right after all."
This article aims to help you reach that state of understanding by examining the technique of updating state during rendering.
Overview of the Technique
First, let's review the technique presented in the official documentation. The following example is quoted from the official docs.
function List({ items }) {
const [isReverse, setIsReverse] = useState(false);
const [selection, setSelection] = useState(null);
// 🔴 Avoid: Adjusting state on prop change in an Effect
useEffect(() => {
setSelection(null);
}, [items]);
// ...
}
This is part of a component that provides the ability to select one item from a list of items. A common requirement is to reset the selection when items changes. In this code, whenever items changes, setSelection(null) is called inside a useEffect to reset the selection state. This is not ideal (reasons explained below).
Instead, the official documentation suggests the following code is better:
function List({ items }) {
const [isReverse, setIsReverse] = useState(false);
const [selection, setSelection] = useState(null);
// Better: Adjust the state while rendering
const [prevItems, setPrevItems] = useState(items);
if (items !== prevItems) {
setPrevItems(items);
setSelection(null);
}
// ...
}
In this code, a state variable prevItems is introduced to store the previous value of items. During rendering, items and prevItems are compared; if they differ, setSelection(null) is called to reset the selection state. This meets the requirement of resetting the selection when items change, while avoiding the use of useEffect.
The key point is that the state update (calling setSelection etc.) happens during rendering. "During rendering" means it occurs not inside an event handler or useEffect, but in the body of the component function (the code executed before the function returns a value).
Why Using useEffect Is Not Good
There are two main reasons why using useEffect in this case is not ideal.
First, it's not the intended use of useEffect. useEffect is meant for implementing "side effects caused by a component's existence," not for "detecting changes in props or other values." In other words, if you use useEffect with the motivation of "I want to detect when items changes," you are deviating from React's declarative mindset, which is undesirable.
Second, it's simply worse from a performance and user experience perspective. Because useEffect runs after rendering is complete, when items changes, there is a brief moment where "items is new but selection hasn't been updated yet," which results in a DOM update. This might cause the user to momentarily see an inconsistent state (this can be mitigated by using useLayoutEffect, but that doesn't change the fact that it's still bad for performance).
Conversely, the technique of updating state during rendering is better for performance. Let's examine this in more detail.
Comparing the Two Methods
Consider a three-level nested component structure as shown below. console.log is used to confirm when each function component is called.
const Wrapper: React.FC = () => {
console.log("Wrapper");
return (
<div>
<List />
</div>
);
};
const List: React.FC = () => {
console.log("List");
const [value, setValue] = useState(0);
useEffect(() => {
console.log("useEffect value:", value);
});
return (
<ul>
<Item />
<Item />
<Item />
</ul>
);
};
const Item: React.FC = () => {
console.log("Item");
return <li>Item</li>;
};
When rendering <Wrapper />, the console output is as follows (functions are called twice in StrictMode, but we omit that for now):
Wrapper
List
Item
Item
Item
useEffect value: 0
Now, let's implement two approaches for the List component: one that updates state in useEffect, and one that updates state during rendering.
Using useEffect
const List: React.FC = () => {
const [value, setValue] = useState(0);
console.log("List", value);
useEffect(() => {
if (value === 0) {
// We don't like value being 0, so set it to 1
setValue(1);
}
});
return (
<ul>
<Item />
<Item />
<Item />
</ul>
);
};
Rendering <Wrapper /> gives the following console output:
Wrapper
List 0
Item
Item
Item
useEffect value: 0
List 1
Item
Item
Item
useEffect value: 1
This shows that first, rendering completes with value equal to 0, then the useEffect fires. After that, setValue(1) triggers a re-render, and rendering occurs again with value equal to 1.
Updating State During Rendering
Now, let's try updating state during rendering without using useEffect.
const List: React.FC = () => {
const [value, setValue] = useState(0);
console.log("List", value);
if (value === 0) {
// We don't like value being 0, so set it to 1
setValue(1);
}
useEffect(() => {
console.log("useEffect value:", value);
});
return (
<ul>
<Item />
<Item />
<Item />
</ul>
);
};
Rendering <Wrapper /> gives:
Wrapper
List 0
List 1
Item
Item
Item
useEffect value: 1
From this result, we can observe the following:
First, because the state was updated during List's rendering, List's rendering was interrupted and restarted. Notably, unlike the useEffect approach, when value is 0, the child Item components of List were not rendered. The List's rendering immediately restarted with the new state, and the Item components were rendered only when value was 1.
Furthermore, the useEffect fired only once, and only when value was 1. The rendering never completed with value at 0, so the useEffect did not fire for that state.
Thus, the two methods lead to significantly different rendering behavior. When state is updated during rendering, the rendering is restarted without completing. The rendering with value equal to 0 was interrupted, so its result was never committed to the DOM, and useEffect didn't fire for it.
This is the performance difference explained in the official documentation.
Note: Only Your Own State Can Be Updated
This technique has a limitation: you can only update the state of the component itself during rendering. You cannot update the state of a parent component or a sibling component. For example, the following code does not work:
const Parent: React.FC = () => {
const [value, setValue] = useState(0);
return <Child setValue={setValue} />;
};
const Child: React.FC<{ setValue: React.Dispatch<React.SetStateAction<number>> }> = ({ setValue }) => {
// ❌ This does not work
setValue(1);
return <div>Child</div>;
};
When rendering <Parent />, the setValue(1); line throws the following error:
Cannot update a component (
Parent) while rendering a different component (Child). To locate the bad setState() call insideChild, follow the stack trace as described in https://react.dev/link/setstate-in-render
Therefore, the ability to update state during rendering is limited to a component's own state.
Alignment with React's Design
I understand this feature as a mechanism for component self-correction. A component can automatically correct its own state when it detects an inconsistency (the official documentation describes this as "adjusting state").
To achieve this, React restarts the rendering. As a result, the List function may be called twice to produce a single render outcome.
This pattern of calling a function component multiple times before rendering completes is common in modern React. Suspense works in a similar way: if a component suspends during rendering, its rendering is interrupted and restarted once the data is available.
Moreover, StrictMode has always called function components twice in development, a behavior that existed since React 16. While the basic assumption in React 16 was that one function call equals one render, the idea that this isn't always guaranteed was already established back then.
A distinctive feature of React as a UI library (especially from version 18 onward) is its advanced rendering scheduling capabilities. React controls "when and where to call which function component" to optimize the final user experience. In other words, we delegate to React the control over when components are called as functions. That's why we must be prepared for a function component to be called multiple times during a single render.
Considering this, having a component self-correct its state during rendering and trigger a re-render is not a significant departure from React's philosophy.
In React, the performance impact of one extra function component call is negligible. With that as a given, React balances declarative UI description with UX optimization. Additionally, as mentioned, this feature can only update the component's own state—a constraint that minimizes negative performance effects. While re-rendering an entire component tree multiple times unnecessarily would be wasteful, restricting the impact to a single function component keeps the cost acceptable. Skipping the rendering of child components when a restart occurs is also part of this balanced design: it repeats function calls when necessary but avoids unnecessarily degrading performance.
Reinterpreting the Technique with the Self-Correction Mindset
Let's revisit the code quoted from the official documentation in the introduction, interpreting it through the lens of "component self-correction."
function List({ items }) {
const [isReverse, setIsReverse] = useState(false);
const [selection, setSelection] = useState(null);
// Better: Adjust the state while rendering
const [prevItems, setPrevItems] = useState(items);
if (items !== prevItems) {
setPrevItems(items);
setSelection(null);
}
// ...
}
The state variable prevItems is used to store the previous items value, as its name suggests.
However, with a self-correction perspective, we can see it differently: prevItems represents "which items the List component believes it is currently rendering."
Normally, items and prevItems are the same. But when the parent component passes new items, items and prevItems diverge—this is an inconsistency. It means "the List thinks the list of options is prevItems, but the parent is telling it something different."
The List component detects this inconsistency and performs self-correction. It reasons that selection is only valid for prevItems and is meaningless for the new items, so it resets selection. It then updates prevItems to the new items. Thus, the component has self-corrected its state to align with the parent's instructions (the new items).
From this viewpoint, the name prevItems might be slightly misleading. A name like currentItems would more accurately convey that the List component is aware of "the items it is currently rendering." A refactored version would look like this:
function List({ items }) {
const [isReverse, setIsReverse] = useState(false);
const [selection, setSelection] = useState(null);
const [currentItems, setCurrentItems] = useState(items);
if (items !== currentItems) {
setCurrentItems(items);
setSelection(null);
}
return (
<ul>
{currentItems.map((item) => (
// ...
))}
</ul>
);
}
A name like prevItems carries a more procedural connotation of "detecting a change." It also forces you to think about the concept of "previous render." With a declarative UI, you'd rather focus on computing the UI for the "current moment."
In contrast, currentItems aligns with the self-correction mindset. It allows you to think in terms of comparing currentItems (your current belief) with items (the parent's instruction) to detect inconsistency, which is more declarative.
The official documentation might have chosen prevItems because the mental model of "detecting a change" is easier for many React users to grasp. React's official docs are excellent and offer deep learning for advanced users, but they sometimes prioritize accessibility over perfection, assuming a broad target audience.
However, now that you've learned about the self-correction concept, I encourage you to try naming like currentItems. Removing procedural mental models from your components makes the code easier to understand and improves maintainability.
But again, I want to emphasize that this technique should not be overused. Ideally, you wouldn't need currentItems at all—you could treat the parent's items as the single source of truth. This technique becomes necessary only when the component's design requires that "the selection state depends on the current items" (in other words, when items changes, an inconsistency with selection must be detected), leading to the need for the component to maintain its own belief (currentItems) separate from the parent's passed items.
Note: Is Purity Preserved?
As you know, React requires function components to be "pure." That is, given the same props and state, they should always return the same result and should not have side effects.
This raises the question: "Isn't updating state during rendering a side effect?"
In my interpretation, it's not a problem. Because "updating state and scheduling a re-render" is itself a kind of result of the rendering. React's concept of "purity" is broader than that in general functional programming; a component can have various "results" besides its return value. For instance, a component suspending (which internally throws an exception) is also a form of result.
What would violate purity is "having different behavior (whether or not to restart rendering) for the same props and state." In the code presented in this article, the behavior for the same props and state is always consistent (it either restarts or not). Therefore, the purity demanded by React is maintained.
The fact that state updates are restricted to the component's own state also reinforces this view. If you could update another component's state, the rendering result would no longer be local to that component, which would indeed be a side effect.
Important Note: You Must Still Return a Value
Finally, let's discuss an important caveat of this technique: even if you schedule a re-render, the component function must still return a value. For example, the following code will not work correctly:
const List: React.FC = () => {
const [value, setValue] = useState(0);
console.log("List", value);
if (value === 0) {
// We don't like value being 0, so set it to 1
setValue(1);
throw new Error("Gyaaa~~~!");
}
useEffect(() => {
console.log("useEffect value:", value);
});
if (value === 0) {
return null;
}
return (
<ul>
<Item />
<Item />
<Item />
</ul>
);
};
When a re-render is scheduled, the component's return value is not used, so it might seem pointless to return anything. You might think it's okay to throw an error and abort at that point.
However, as shown above, if you throw an error, the "error thrown" takes precedence over "state updated." In other words, the rendering result becomes "an error occurred" rather than "update state and restart." The error would then be caught by an error boundary. Therefore, even if you schedule a re-render, you still need to properly return a value.
The following approach is also invalid:
const List: React.FC = () => {
const [value, setValue] = useState(0);
console.log("List", value);
if (value === 0) {
// We don't like value being 0, so set it to 1
setValue(1);
return null; // ❌
}
useEffect(() => {
console.log("useEffect value:", value);
});
return (
<ul>
<Item />
<Item />
<Item />
</ul>
);
};
This doesn't throw an error, but it returns null when it determines a re-render is needed. However, this violates the rules of hooks.
The rules of hooks require that hooks are not called conditionally. In the code above, when value is 0, useEffect is not called, but when value is 1, it is called. This violates the rules of hooks. We must abide by these rules even when a re-render is scheduled.
Thus, even when a re-render is scheduled, the component function must always return a value and must follow the rules of hooks. If an inconsistency has occurred and the return value is meaningless, a good approach is the following:
const List: React.FC = () => {
const [value, setValue] = useState(0);
console.log("List", value);
if (value === 0) {
// We don't like value being 0, so set it to 1
setValue(1);
}
useEffect(() => {
console.log("useEffect value:", value);
});
if (value === 0) {
// Inconsistent state, skip calculating the return value
return null;
}
return (
<ul>
<Item />
<Item />
<Item />
</ul>
);
};
In this way, returning null after all hooks have been called is fine. Since the return value of List is not used once a re-render is scheduled, returning null is acceptable (it will not momentarily appear on the screen).
This approach requires writing a conditional branch like value === 0 in two places (or introducing a flag to avoid duplication), which is somewhat verbose. It's a constraint of React. Personally, I think this constraint could potentially be relaxed, but for now it's necessary.
Summary
In this article, we explored the technique of updating state during rendering, showing that it is actually a viable technique that does not contradict React's design.
Adopting the idea of component self-correction helps in understanding how this technique aligns with React's design philosophy. A component can automatically correct its own state when it detects an inconsistency.
Thus, you can equip your components with a self-correction mechanism. Knowing this will broaden the possibilities in component design.
Discussion