Course contentsShow
← React
Lesson 2326 of 2,39650. Performance: Optimization TechniquesFree lesson

Context Selector Pattern with useSyncExternalStore

Building or using libraries that let consumers subscribe to specific slices of context to prevent over-rendering.

Context Selector Pattern with useSyncExternalStore

What you'll learn: How to build or use libraries that let components subscribe to only specific slices of context, preventing unnecessary re-renders.

The Core Problem

When you put an object in context, every consumer re-renders when any part of that object changes—even if a component only cares about one field. You've learned to split contexts, but sometimes you need a single large state object with surgical subscription control.

How useSyncExternalStore Enables Selectors

useSyncExternalStore is a React hook that lets you subscribe to external stores. You can use it to create a selector pattern where components only re-render when their selected slice of context actually changes.

The pattern works like this:

  1. Store your context value in a ref (doesn't cause re-renders)
  2. Track subscribers who want notifications
  3. Each component subscribes with a selector function that picks what it needs
  4. Only notify subscribers when their specific selection changes

The Analogy

Think of context like a newspaper. The normal pattern delivers the entire newspaper to every subscriber daily—even if you only read sports. The selector pattern lets you subscribe to just the sports section, and you only get a delivery when that section changes.

Libraries vs DIY

Building this yourself requires managing subscriptions, equality checks, and refs carefully. Most teams use libraries like:

  • use-context-selector
  • zustand (which can wrap context)
  • Custom wrappers around useSyncExternalStore

These libraries handle the boilerplate while you just write: const userName = useContextSelector(ctx, state => state.user.name)

Key Takeaway: The context selector pattern with useSyncExternalStore lets components subscribe to specific slices of context state, re-rendering only when their selected data changes—solving the "entire context re-renders everything" problem without splitting into dozens of contexts.