CodeBlanks Logo Icon CodeBlanks

What is context?

Learn that context is a way to share data instead of prop drilling.

What is context?

Context is React's official way to pass data deep into the component tree. Normally you carry data through props hand to hand; this is known as prop drilling.

Prop drilling is fine in short trees, but once you go four or five levels deep, intermediate components must carry data they don't use. Context delivers data straight to where it's needed.

Typical uses: theme (dark/light), language (tr/en), logged-in user. This data is read in many places and passing it through props is tiring.

When to use context?

Context is not for every case. For two or three levels deep, props still work well and read clearly. Save context for data that feels global.

Good candidates: theme, locale, auth state, global notifications. Bad candidates: form data of one component or items for one list — those stay as local state.

Every change in context re-renders all consumers. So putting very frequently changing data in context can hurt performance; we'll see solutions in advanced level.

Practice ThemeTitle context

Complete the skeleton. Create a context object called ThemeContext; pass "light" as the default value to createContext. Export the result.

Starter code

App.jsx
// Define ThemeContext here
import { createContext } from "react";

Sample solution

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

const ThemeContext = createContext("light");

export default ThemeContext;

Questions and answers

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

1 What does prop drilling mean?

  • Lifting state up
  • Passing data through context
  • Passing data through props layer by layer Correct answer
  • Fetching data with useEffect

Explanation: Prop drilling is passing data through props layer by layer.

2 Context usage

Question
Data like theme and language are ____ data, suitable for context.
Answer
Data like theme and language are global data, suitable for context.

Explanation: Global data is ideal for context.

3 Match the context concepts

Term Meaning
Prop drilling Layer-by-layer props
Context Global data
Theme Typical use
useContext Reading hook

All lessons in Beginner