CodeBlanks Logo Icon CodeBlanks

Context separation

Learn to protect performance by splitting multiple contexts.

Context split

A big context re-renders all consumers on every small change. This creates performance issues. The fix: split the context into several smaller contexts.

For example, in a user context, user and setUser are kept in separate contexts. user changes often, setUser never. Components using only setUser avoid needless renders.

This pattern is called state and setter split. React's official docs recommend it too; it brings serious speed gains in large apps.

Two context example

Define a UserStateContext and a UserSetContext. The Provider wraps both; it gives user and setUser as separate values.

On the read side, components needing only setUser use useContext(UserSetContext); they don't render when user changes. Components needing only user read UserStateContext.

So each component listens only to the value it needs. React's render tree runs more efficiently. This approach matters in large lists and forms.

Practice Define two contexts

Complete the skeleton. Create two contexts called UserStateContext and UserSetContext; both with null defaults. Export both.

Starter code

App.jsx
import { createContext } from "react";

// Define the two contexts here

Sample solution

App.jsx
import { createContext } from "react";

const UserStateContext = createContext(null);
const UserSetContext = createContext(null);

export { UserStateContext, UserSetContext };

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why split context?

  • To write less code
  • For performance Correct answer
  • To skip useEffect
  • To change CSS

Explanation: Splitting context is for performance.

2 Split pattern

Question
Frequently changing ____ and never-changing setter are kept in separate contexts.
Answer
Frequently changing state and never-changing setter are kept in separate contexts.

Explanation: state and setter are kept separate.

3 Match the context split

Term Meaning
UserStateContext user
UserSetContext setUser
Provider Wraps
useContext Reads

All lessons in Intermediate