CodeBlanks Logo Icon CodeBlanks

useContext

Learn to consume context with useContext.

What is useContext?

useContext is the hook that reads a value from a context. When you write const theme = useContext(ThemeContext) you get the value provided by the nearest Provider. If no Provider exists, the context's default value is returned.

A component using useContext re-renders automatically when the context value changes. This removes the need to pass data via props. useContext always reads the value of the nearest Provider; if Providers nest, the innermost one wins. Import the hook from the react package: import { useContext } from "react".

Using useContext

To call useContext you first import the relevant context. Then you write const theme = useContext(ThemeContext). After that the theme variable works like a state; but updates happen not with setState but by changing the Provider's value.

An important point: every time you call useContext, React subscribes that component to context changes. When the Provider's value changes, all subscribed components re-render. So keep context only for truly global data; for frequently changing values that only a few components care about, state may be a better fit.

Practice Read the theme with useContext

Write a ThemedText component. Read the theme value from ThemeContext with useContext. The component returns <Text>{theme}</Text>. Define ThemeContext outside.

Starter code

App.js
// Import useContext and createContext

// Create ThemeContext with createContext; default "light"

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

  return <Text>Theme</Text>;
}

Sample solution

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

const ThemeContext = createContext("light");

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

Questions and answers

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

1 What does useContext return?

App.js
const theme = useContext(ThemeContext);
  • The Provider component
  • Always the default value
  • Context nesnesini
  • The nearest Provider's value Correct answer

Explanation: useContext returns the value of the nearest Provider.

2 Call useContext

Question
const theme = ____(ThemeContext);
Answer
const theme = useContext(ThemeContext);

Explanation: useContext reads the value.

3 Match the concept to its role

Term Meaning
useContext Reads the value
ThemeContext Context object
Provider Provides the value
theme Read value

All lessons in Intermediate