Skip to content
Node.js Sounds Complicated? This Article Makes It Click

React Context API Explained – How to Create Global Values

React Context lets a parent component provide values globally to its entire component tree, regardless of depth. It is an excellent alternative to prop drilling.

This post provides a snapshot of the Code React Sweetly book. It serves as a quick reference guide.

There are three main steps to using context in React. These are:

  1. Create a context object with a default value.
  2. Use the context value in any component that needs it.
  3. Optionally override the default context value by providing new data to all of a parent component’s descendants, regardless of depth.
import { createContext, useContext } from "react";
// Create context object
const NameOfContextObject = createContext(defaultValue);
function ParentComponent() {
// Provide new context value
return (
<NameOfContextObject value={contextValue}>
<ChildComponent />
</NameOfContextObject>
);
}
function ChildComponent() {
// Use context value
const contextValue = useContext(NameOfContextObject);
return <jsx>{contextValue}</jsx>;
}

Here’s what’s going on:

  • import statement: Import the createContext and useContext APIs from the React library.
  • NameOfContextObject: A variable for storing the context object.
  • createContext: The React function for creating a new context object.
  • defaultValue: An optional fallback used when no provider exists in a component’s ancestor tree. It is static and does not change over time. If omitted, React will use undefined.
  • ParentComponent: The component providing context data to its descendant components.
  • <NameOfContextObject>...</NameOfContextObject>: A wrapper used to access the context object’s Provider property.
  • value={contextValue}: A required prop used to specify the context value for all the components the wrapper encloses. It can be any valid JavaScript data type. If omitted, the context will be undefined and React will throw an error.
  • ChildComponent: A descendant component that can use the useContext Hook to consume the parent component’s contextValue.
  • useContext: The React Hook for reading (consuming) the value of a specified context object.
import { createContext, useContext } from "react";
import { createRoot } from "react-dom/client";
// Create context object
const NumberContext = createContext(0);
function App() {
// Provide new context value
return (
<NumberContext value={321}>
<Number />
</NumberContext>
);
}
function Number() {
// Use context value
const number = useContext(NumberContext);
console.log(number); // Outputs: 321
return <h1>Number: {number}</h1>;
}
const root = createRoot(document.getElementById("root"));
root.render(<App />);

Try it on CodeSandbox

In the snippet above, <App> uses the NumberContext provider to provide context value to all its descendant components.

  • To improve performance and prevent bugs, always define Context objects outside your components. Creating context objects inside components creates a new object on every render, which makes React re-render components unnecessarily and can cause subtle bugs.
  • When you create a context, always supply a valid default value or set it to null. This ensures that if a child component is rendered outside a provider, your app can safely handle the case instead of throwing errors.
  • Prop drilling works well in small projects where passing data through a few levels is easy. In larger or more complex component trees, prefer React Context if prop drilling leads to complex code or reduces efficiency.

The Code React Sweetly book is a beginner-friendly guide covering all aspects of React Context, including:

  • Explore React Context, how it works, and its role in global data management without prop drilling.
  • Learn to create and use Context objects, provide values across component trees, override values in child components, and share Context between files.
  • Learn how to build dynamic Context values with React state.
  • Understand the key best practices every React developer should know.

A Beginner's Guide to React: Learn JSX, Hooks, and Real-World App Development