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

Creating a Context with createContext

How use-context-selector's createContext differs from React's native version and sets up selective subscription.

Creating a Context with createContext

You'll learn how use-context-selector's createContext differs from React's built-in version and enables selective subscription to prevent unnecessary re-renders.


The Native React Version Recap

React's native createContext returns a context object where any consumer re-renders whenever any part of the context value changes. You've seen this problem: change one field in an object, and every component using that context re-renders—even if they don't care about that specific field.

The use-context-selector Alternative

The use-context-selector library provides its own createContext function that looks similar but works differently under the hood:

import { createContext } from 'use-context-selector';

// Looks familiar, but enables selective subscriptions
const UserContext = createContext({ name: '', age: 0 });

What's Different?

While the syntax is nearly identical to React's version, this context is designed to work with the library's special hooks (like useContextSelector) that let components subscribe to specific slices of the context value.

Think of it like signing up for news alerts: React's native context makes you subscribe to all news categories at once. The use-context-selector version lets you say "I only want sports updates"—so you don't get notifications about politics, weather, or entertainment.

The Setup

You use it exactly like React's createContext:

import { createContext } from 'use-context-selector';

const ThemeContext = createContext({ 
  color: 'blue', 
  fontSize: 16 
});

The magic happens when you consume this context with the library's specialized hooks, which you'll learn next.

Key Takeaway: use-context-selector's createContext creates a context that supports selective subscriptions, preventing unnecessary re-renders when only part of the context value changes.