Skip to main content

How do you create a Context?

Step 1. Import createContext

javascript
import { createContext } from "react";

Step 2. Create the context itself

javascript
export const ThemeContext = createContext("light");

What createContext(defaultValue) does:

  • creates a context object;
  • defaultValue is used only when there is no <Provider> higher up the tree.

Usually defaultValue is set only for types (e.g. with TypeScript) or for tests.


Step 3. Wrap the needed part of the app in a Provider

javascript
import { ThemeContext } from "./ThemeContext"; function App() { return ( <ThemeContext.Provider value="dark"> <Toolbar /> </ThemeContext.Provider> ); }

What the Provider does:

  • makes the value (value="dark") available to all child components;
  • when value changes -> all consumers re-render.

Step 4. Use the context inside a component

javascript
import { useContext } from "react"; import { ThemeContext } from "./ThemeContext"; function Button() { const theme = useContext(ThemeContext); return <button className={theme}>Theme: {theme}</button>; }

What useContext(Context) does:

  • returns the current value of the context (from the nearest Provider);
  • the component re-renders automatically when this value changes.

Full example:

javascript
// ThemeContext.js import { createContext } from "react"; export const ThemeContext = createContext("light"); // App.jsx import { ThemeContext } from "./ThemeContext"; import Button from "./Button"; export default function App() { return ( <ThemeContext.Provider value="dark"> <div> <h1>Context example</h1> <Button /> </div> </ThemeContext.Provider> ); } // Button.jsx import { useContext } from "react"; import { ThemeContext } from "./ThemeContext"; export default function Button() { const theme = useContext(ThemeContext); return <button className={theme}>Current theme: {theme}</button>; }

Common mistakes and tips

MistakeHow to fix it
Using useContext without a ProviderAdd a <Context.Provider> higher up the tree
Every re-render of App changes the value={{user}} objectWrap value in useMemo
Using a single context for everythingSplit by meaning: ThemeContext, AuthContext, LangContext, etc.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.