Course contentsShow
← React
Lesson 861 of 2,39622. Context PerformanceFree lesson

Selector Stability and Performance

Why selector functions should be stable references or inline, and how they affect subscription behavior.

Selector Stability and Performance

What you'll learn: How the stability of your selector functions affects useContextSelector performance and when re-renders occur.

The Subscription Mechanism

When you use useContextSelector(MyContext, selector), React subscribes to your context and runs your selector function every time the context value changes. The library compares the result of your selector to decide if your component should re-render.

Here's the catch: if your selector function itself changes identity on every render, the subscription mechanism may behave unexpectedly or lose optimizations.

Inline vs Stable Selectors

You have two safe options:

Inline selectors are perfectly fine:

const userName = useContextSelector(UserContext, (state) => state.user.name);

The library handles inline functions efficiently because it compares selector results, not the function reference itself.

Stable references work great for reusable or complex logic:

const selectUserName = (state) => state.user.name;

function UserGreeting() {
  const name = useContextSelector(UserContext, selectUserName);
  return <h1>Hello, {name}</h1>;
}

What to Avoid

Creating a new selector in a dependency array or passing one from a parent can cause issues:

// ❌ Problematic: new function every render from parent
<UserGreeting selector={(s) => s.user.name} />

The key principle: selector functions should either be defined inline at the call site or defined outside the component as stable references. Don't create them dynamically unless you memoize them with useCallback.

Key Takeaway: Selector functions for useContextSelector should be inline or stable references—avoid creating new selector functions on every render, as this can interfere with the library's optimization strategy.