Skip to content

[Suggestion]: lazy initialization example can encourage unsafe patterns - show example #8677

Description

@gmoniava

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions