Summary
Show example when lazy initialization example can be unsafe.
Page
https://react.dev/reference/rules/components-and-hooks-must-be-pure#lazy-initialization
Details
The lazy initialization section currently presents this pattern as valid:
function ExpenseForm() {
SuperCalculator.initializeIfNotReady(); // ✅ Good: if it doesn't affect other components
// Continue rendering...
}
However, I think this example is easy to generalize into a dangerous pattern:
if (ref.current === null) {
ref.current = createResource();
}
For resources with a lifecycle - subscriptions, event listeners, timers, connections, etc. - creating the resource during render is unsafe because a render is not guaranteed to result in a committed effect.
For example:
function useLegacyStore() {
const subscriptionRef = useRef(null);
if (subscriptionRef.current === null) {
subscriptionRef.current = store.subscribe(() => {
// ...
});
}
useEffect(() => {
return () => {
subscriptionRef.current?.unsubscribe();
};
}, []);
}
This can appear to work when components only render as part of normal mount/unmount flows. However, with concurrent rendering or APIs such as Activity, React may render a component without subsequently mounting the
Effect associated with that render.
The subscription has already been created, while its cleanup is tied to an Effect that may never run.
The documentation should make this distinction explicit, perhaps by adding a warning/example.
Inspired by:
https://hackernoon.com/react-activity-when-a-render-no-longer-guarantees-an-effect
Summary
Show example when lazy initialization example can be unsafe.
Page
https://react.dev/reference/rules/components-and-hooks-must-be-pure#lazy-initialization
Details
The
lazy initializationsection currently presents this pattern as valid:However, I think this example is easy to generalize into a dangerous pattern:
For resources with a lifecycle - subscriptions, event listeners, timers, connections, etc. - creating the resource during render is unsafe because a render is not guaranteed to result in a committed effect.
For example:
This can appear to work when components only render as part of normal mount/unmount flows. However, with concurrent rendering or APIs such as Activity, React may render a component without subsequently mounting the
Effect associated with that render.
The subscription has already been created, while its cleanup is tied to an Effect that may never run.
The documentation should make this distinction explicit, perhaps by adding a warning/example.
Inspired by:
https://hackernoon.com/react-activity-when-a-render-no-longer-guarantees-an-effect