CodeBlanks Logo Icon CodeBlanks

Summary - Context

Combine createContext, Provider and useContext to write a theme system.

Summary - Context

In this group you learned the Context API. With createContext you create a context, with a Provider you supply a value, with useContext you read it. The default value steps in when no Provider exists.

Now you will combine these four pieces into a theme system. A parent component holds the theme as state, hands it down through a Provider; child components read the theme with useContext and update the screen colour accordingly. This is a core pattern you will meet in real apps.

Practice Create the theme context

Create ThemeContext. With createContext give the default value "light". Then log it with console.log(ThemeContext).

Starter code

App.js
// Import createContext

// Create ThemeContext with createContext; default "light"
// Log ThemeContext

Sample solution

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

const ThemeContext = createContext("light");
console.log(ThemeContext);

Practice Combine Provider and useContext

Write an App component. Hold theme with useState (initial value "dark"). Wrap <ThemedText /> with <ThemeContext.Provider value={theme}>. The ThemedText component reads the theme with useContext(ThemeContext) and returns <Text>{theme}</Text>.

Starter code

App.js
// Import createContext, useState and useContext

// Create ThemeContext with createContext; default null

function ThemedText() {
  // Read theme value from ThemeContext with useContext

  return <Text>Theme</Text>;
}

function App() {
  // Hold theme state with useState; initial "dark"
  // Wrap <ThemedText /> with Provider; pass theme to value

  return <ThemedText />;
}

Sample solution

App.js
import { createContext, useContext, useState } from "react";
import { Text } from "react-native";

const ThemeContext = createContext(null);

function ThemedText() {
  const theme = useContext(ThemeContext);
  return <Text>{theme}</Text>;
}

function App() {
  const [theme, setTheme] = useState("dark");
  return (
    <ThemeContext.Provider value={theme}>
      <ThemedText />
    </ThemeContext.Provider>
  );
}

Questions and answers

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

1 What problem does Context solve?

App.js
const ThemeContext = createContext("light");
  • Prop drilling Correct answer
  • Folder structure
  • Component styles
  • AsyncStorage

Explanation: Context solves prop drilling.

2 Match each piece to its role

Term Meaning
createContext Creates the context
Provider Provides the value
useContext Reads the value
default Returns without Provider

3 Create the context

Question
const ThemeContext = ____("light");
Answer
const ThemeContext = createContext("light");

Explanation: createContext creates the context.

All lessons in Intermediate