createContext

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 2 min

createContext

createContext is a React API used to create a Context object. This object allows you to share data (state, functions, configuration) deeply throughout your component tree without passing props manually.

Syntax

import { createContext } from 'react';

const MyContext = createContext(defaultValue);
  • defaultValue: The value that a consuming component will receive if it does not have a matching Provider above it in the tree. This is mostly useful for testing components in isolation. If you don’t have a meaningful default, you can pass null.

What does it return?

createContext returns a Context object. This object does not hold state itself. Instead, it serves as a “key” or “identifier” that contains two important React components:

  1. MyContext.Provider: Used higher up in the component tree to provide the actual value.
  2. MyContext.Consumer: (Legacy) Used deeper in the tree to read the value. In modern React, you use the useContext Hook instead.

Example

Usually, you create the context in a dedicated file so it can be easily imported by both the Provider and the consumers.

// ThemeContext.js
import { createContext } from 'react';

// The default value is 'light'
export const ThemeContext = createContext('light');
// App.js
import { ThemeContext } from './ThemeContext';

export default function App() {
  // We use the Provider to override the default 'light' value with 'dark'
  return (
    <ThemeContext.Provider value="dark">
      <Navbar />
    </ThemeContext.Provider>
  );
}

The defaultValue Fallback

It’s a common misconception that the defaultValue passed to createContext acts as the initial state for your app. It does not.

The defaultValue is only used when a component calls useContext(MyContext) but there is no Provider for that context anywhere above it in the component tree.

If there is a Provider above it, but the Provider’s value is explicitly set to null or undefined, the consumer will receive null or undefined, not the defaultValue.

// Context has a default of 'blue'
const ColorContext = createContext('blue');

function Component() {
  // Reads 'blue' because there is no Provider wrapping this component
  const color = useContext(ColorContext); 
  return <div style={{ color }}>Text</div>;
}

Interview Questions

Q: What exactly does the default value passed to createContext(defaultValue) do?
A: It is only ever used when a component calls useContext but there is NO matching <Provider> anywhere above it in the component tree. It is extremely useful for providing safe defaults for Unit Tests so you don’t have to wrap every tested component in a mock Provider.