why some react libs prefer to do const [] = React.useState instead of React.useMemo when they want to ensure unique instance per request (eg in nextjs)
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Excellent question. This is a subtle but very important distinction in modern React, and it reveals a deep understanding of the React component lifecycle.
The core reason libraries prefer const [instance] = React.useState(() => new MyClass()) over React.useMemo() is for a semantic guarantee of stability.
Let's break it down.
The Two Patterns
First, let's look at what you're asking about.
Pattern 1: The useState Initializer
javascript
import React from 'react';
import { ApiClient } from './api';
function MyComponent() {
// The function `() => new ApiClient()` is a "lazy initializer".
// It only runs ONCE, when the component first mounts.
const [apiClient] = React.useState(() => new ApiClient());
// ... use apiClient for requests
return <div>...</div>;
}
Pattern 2: The useMemo with Empty Dependencies
javascript
import React from 'react';
import { ApiClient } from './api';
function MyComponent() {
// The function `() => new ApiClient()` runs once, and the result is memoized.
const apiClient = React.useMemo(() => new ApiClient(), []); // <-- empty dependency array
// ... use apiClient for requests
return <div>...</div>;
}
On the surface, they look like they do the same thing: create a single instance of ApiClient for the lifetime of the component. And in 99% of cases, they will behave identically. The difference lies in the guarantees that React provides.
The Crucial Difference: Guarantee vs. Optimization
useState offers a semantic GUARANTEE.
The React documentation is explicit about this. The lazy initializer function for useState is guaranteed to run only once for the entire lifecycle of the component instance. It's effectively the "constructor" for functional components. Once the state is initialized, React will never discard it and re-run the initializer unless the entire component is unmounted.
useMemo is a performance OPTIMIZATION, not a guarantee.
The React documentation is also explicit about this. While useMemo with an empty dependency array [] will usually run only once, React reserves the right to "forget" the memoized value and re-run the calculation on a subsequent render. This might happen, for example, to free up memory in future versions of React or in offscreen components.
From the React Docs:
You may rely on useMemo as a performance optimization, not as a semantic guarantee. In the future, React may choose to “forget” some previously memoized values and recalculate them on next render... Write your code so that it still works without useMemo — and then add it to optimize performance.
Why This Matters for a Library Author (and in Next.js)
A library author cannot make assumptions about how their component will be used. They need to write code that is robust and correct in all situations.
Scenario: Imagine a library that provides a component for making API calls. This component needs a single, stable instance of an HTTP client (like axios or a custom class) that might hold things like authentication tokens, request queues, or connection state.
If they use useState: They are guaranteed that this client instance will never be re-created during re-renders. The identity of the object is stable. Any state held within that apiClient object (e.g., a refresh token) will be preserved. This is safe and predictable.
If they use useMemo: There is a small but non-zero chance that React could discard the memoized apiClient instance and create a new one on a re-render. If that happens, any internal state within the old client is lost. This could lead to unpredictable bugs, like losing authentication status or dropping in-flight requests.
Connecting to the "Per Request" in Next.js:
On the server (during Server-Side Rendering), a component renders exactly once per request. In this specific context, both useState and useMemo would behave identically—their initializer function would run exactly one time.
So why the preference? Consistency and Client-Side Safety.
The same component rendered on the server is also sent to the client to be "hydrated." On the client, this component can live on and re-render many times. The library author must write code that works correctly both on the server and on the client.
By choosing useState, they use a pattern that is guaranteed to be correct everywhere:
On the Server (per request): Creates one instance.
On the Client (during hydration and re-renders): Preserves that one instance, guaranteeing its identity.
Using useMemo would work on the server but introduces a potential (though currently rare) point of failure on the client. For a library, that risk is unacceptable.
Summary Table
Feature
const [val] = useState(() => ...)
const val = useMemo(() => ..., [])
Purpose
To initialize a stateful value that persists for the component's lifetime.
To memoize the result of an expensive calculation to avoid re-computing it on every render.
Guarantee
Guaranteed to run the initializer only once per component lifecycle.
Not guaranteed. React may re-run the calculation if it "forgets" the value.
When to Use
When you need a stable instance of a class, object, or any value whose identity must not change across re-renders (e.g., API clients, state machines, event emitters).
When you are calculating a value derived from props/state, and the calculation is expensive. If it were re-calculated, the logic would still be correct, but performance would suffer.
Analogy
The constructor of a class component.
A cache for a pure function's result.
Conclusion:
When a library needs to ensure a single, unique, and stable instance of an object for the entire life of a component, useState with a lazy initializer is the semantically correct and safest choice. It provides a rock-solid guarantee that useMemo explicitly does not.