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:
- Store your context value in a ref (doesn't cause re-renders)
- Track subscribers who want notifications
- Each component subscribes with a selector function that picks what it needs
- 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-selectorzustand(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.