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

useContextSelector Hook

Using the selector function to extract only the data you need, preventing unnecessary re-renders.

useContextSelector Hook

What you'll learn: How to extract only the specific data you need from context to prevent unnecessary component re-renders.

The Selective Reading Problem

You've created a context with use-context-selector's createContext. Now you need to read from it. The traditional useContext hook subscribes your component to all changes in the context value. But what if you only care about one piece of data?

That's where useContextSelector comes in.

How useContextSelector Works

Instead of reading the entire context value, useContextSelector takes two arguments:

  1. The context object (created with createContext)
  2. A selector function that extracts exactly what you need
const userName = useContextSelector(UserContext, (state) => state.user.name);

The selector function receives the full context value and returns just the slice you care about. Your component only re-renders when that specific piece changes, not when anything else in the context updates.

The Performance Win

Think of it like subscribing to a specific channel on TV instead of watching every channel simultaneously. If the user's email changes but their name doesn't, a component selecting state.user.name won't re-render at all.

// This component only re-renders when the theme changes
const theme = useContextSelector(AppContext, (state) => state.theme);

// This component only re-renders when count changes
const count = useContextSelector(AppContext, (state) => state.count);

The library compares the result of your selector function between renders. If the returned value hasn't changed, your component stays put.

Key Takeaway: useContextSelector lets you cherry-pick exactly which data triggers re-renders, solving the selective subscription problem that plain Context can't handle efficiently.