Loading

Quipoin Menu

Learn • Practice • Grow

react / createContext and Provider
tutorial

createContext and Provider

Now that you understand what Context API is, let's learn how to create a context and provide values to components using the `Provider`. This is the first step to making data available anywhere in your component tree.

Creating a Context

You create a context using `React.createContext()`. This returns an object with two properties: `Provider` and `Consumer`. You typically create context in a separate file and export it.
<!-- ThemeContext.js -->
import React from 'react';

const ThemeContext = React.createContext('light'); <!-- default value -->

export default ThemeContext;

The Provider Component

The `Provider` is a component that wraps the part of your app where you want the context to be available. It accepts a `value` prop that will be passed to all consuming components.
import React, { useState } from 'react';
import ThemeContext from './ThemeContext';
import Toolbar from './Toolbar';

function App() {
  const [theme, setTheme] = useState('light');

  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

Default Value

The argument passed to `createContext` is the default value. It is used when a component consumes the context but is not wrapped inside a matching Provider. This is useful for testing or when you want a fallback.

Nested Providers

You can nest Providers to override the value for a subtree. The nearest Provider wins.
<ThemeContext.Provider value="dark">
  <div>
    <ThemeContext.Provider value="light">
      <Toolbar /> <!-- gets 'light' -->
    </ThemeContext.Provider>
  </div>
</ThemeContext.Provider>

Two Minute Drill

  • Use `React.createContext(defaultValue)` to create a context object.
  • The context object contains `Provider` and `Consumer` components.
  • Wrap your component tree with `` to provide data.
  • The `value` can be any JavaScript value often an object containing state and updater functions.
  • If no Provider is found, components receive the default value.

Need more clarification?

Drop us an email at career@quipoinfotech.com