CodeBlanks Logo Icon CodeBlanks

Context default

Learn context default values and fallback.

What is the default value?

The default value of a context is the value that useContext returns when a component is not inside any Provider. When you write createContext("light"), this default becomes "light".

The default value is used for two purposes. First to give a real starting value: even with no Provider at the root, components keep working. Second to catch mistakes: if you do createContext(null) and a child gets null, you forgot the Provider; this is easy to spot. Which path you choose depends on whether you prefer catching mistakes or flexible running.

Catch mistakes with a null default

Some teams prefer to write createContext(null). With this approach, if a component is used outside a Provider, useContext returns null; the developer notices the mistake at once.

Forgetting a Provider is easy in large apps. When null is returned and a child calls theme.toUpperCase(), it throws; this gives an early warning instead of a silently broken screen. So many teams set the default to null to catch mistakes early. As long as you make sure a Provider exists at the root, this approach works well.

Practice Use the default value

Create a context named LangContext. Use createContext(null). Then write a Picker component; read lang with useContext(LangContext) and log it with console.log(lang).

Starter code

App.js
// Import createContext and useContext

// Create LangContext with createContext; default null

function Picker() {
  // Read lang value from LangContext with useContext
  // Log lang with console.log

  return null;
}

Sample solution

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

const LangContext = createContext(null);

function Picker() {
  const lang = useContext(LangContext);
  console.log(lang);
  return null;
}

Questions and answers

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

1 Give a default value

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

Explanation: "light" becomes the default theme.

2 Match the scenario to the outcome

Term Meaning
Provider exists Provider value returns
No Provider, default null null returns
No Provider, default "light" light returns
useContext call Reads the value

3 When is createContext(null) useful?

App.js
const ThemeContext = createContext(null);
  • AsyncStorage yerine
  • To warn early when the Provider is missing Correct answer
  • For every component's default theme
  • To share styles

Explanation: A null default warns early when a Provider is forgotten.

All lessons in Intermediate