CodeBlanks Logo Icon CodeBlanks

Summary - Context

Set up a theme (dark/light) context and connect two buttons.

Summary - Context

In this group you learned what context is, why it's an alternative to prop drilling, how to create a context object with createContext, provide a value with Provider, and read it with useContext.

The recipe: put global data in context, wrap with a Provider at the top, read with useContext at the bottom. This eliminates prop drilling and keeps code clean.

In the next step you'll combine the provider and the consumer in one file.

Practice Create and read ThemeBadge

Complete the skeleton. Create ThemeContext with default "light". Then write a ThemeBadge component that reads the theme with useContext(ThemeContext) and returns <p>{ '{ theme }' }</p>. Export it.

Starter code

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

// Define ThemeContext and ThemeBadge here

Sample solution

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

const ThemeContext = createContext("light");

function ThemeBadge() {
  const theme = useContext(ThemeContext);
  return <p>{theme}</p>;
}

export default ThemeBadge;

Questions and answers

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

1 Where does useContext read from?

  • From state
  • The nearest Provider Correct answer
  • From props
  • The farthest Provider

Explanation: useContext reads from the nearest Provider.

2 Match the context steps

Term Meaning
createContext Make object
Provider Give value
useContext Read
value Carry data

All lessons in Beginner