Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk4 min

How to Use React Context in Function Components

Create a context outside components, provide it above its readers, and use useContext at the top level of each function component that needs the value.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Create a context once, provide its value above the components that need it, and read it with useContext at the top level of each function component. React gives each reader the value from the nearest matching provider above it in the component tree.

How to use Context: the basic pattern

Context makes information available to descendants without passing it through every intermediate component as props. The three steps are to create a context, place a provider above its readers, and call useContext where the value is needed.

  1. Create the context outside components. Import createContext from React and declare the context at module scope. Use a meaningful default if one is appropriate; otherwise, use null.
  2. Provide a value above the readers. Render the context as a provider around the relevant part of the tree and pass the current value.
  3. Read the value in a function component. Import useContext and call it at the top level of the component, passing the context object.
import { createContext, useContext, useState } from 'react';

const ThemeContext = createContext('light');

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

  return (
    <ThemeContext value={theme}>
      <Toolbar />
    </ThemeContext>
  );
}

function Toolbar() {
  const theme = useContext(ThemeContext);
  return <div className={theme}>Toolbar</div>;
}

This example follows the current provider syntax in React’s createContext documentation. If you are working with a React version whose documentation uses <ThemeContext.Provider value={theme}>, use the syntax supported by that version. The useContext reference explains how consumers find their provider.

Where to create and place a context

Declare it at module scope

Call createContext outside component functions. If the provider and readers are in different files, export the context from a shared module and import the same context object in both places. Context matching is based on the context object, not merely on the variable’s name.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Put the provider above every component that reads it

useContext(ThemeContext) searches upward through the React tree and uses the closest provider for that context. Intermediate components do not need to forward the value. A nested provider of the same context intentionally supplies a different value to its own descendants.

A component cannot read a provider that it returns itself: its own useContext call only sees providers above that component. If the reader needs a value, move the provider into an ancestor or split the provider and reader into separate components. React describes these rules in useContext.

Defaults and changing values

The value passed to createContext(defaultValue) is a static fallback. React uses it only when there is no matching provider above the consumer; it does not act as changing state. To supply dynamic data, render a provider with the current value.

A common approach is to keep the data in state in an ancestor and use that state as the provider value. When the value changes, components reading that context below the provider update. React compares the previous and next values with Object.is. Wrapping a reader in memo does not stop it from receiving a changed context value. See the useContext reference for the update behavior.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Context or props?

Use props when they make a component’s dependencies clearer and the data only needs to travel a short distance. Consider composition with children if intermediate components merely relay information and do not use it themselves. Context is useful when data is needed by components at different depths across a subtree—for example, a theme, current account, routing information, or shared state. React’s guide, Passing Data Deeply with Context, explains this trade-off.

Approach Fits when What to consider
Props A parent passes data to direct children or through a manageable chain. Dependencies are explicit at each component boundary, but intermediate components may need to relay values they do not use.
Children composition Intermediate components only need to position or wrap a component that uses the data. Can avoid threading a value through components that do not consume it.
Context Multiple descendants across a subtree need the same information. Readers depend on the context provider above them; nested providers can give separate subtrees distinct values.

There is no universal performance ranking between props and context established by these API references. Choose based on the shape of the component tree and how clearly you want dependencies to be expressed.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Context values, objects, and rendering

Context values can be objects or functions as well as strings and other values. If a provider’s parent creates a fresh object or function on every render, its identity changes; that can cause context readers to render again even when the information inside is effectively unchanged.

Do not add memoization automatically. If that extra work matters in your component, React’s useContext guidance shows how to stabilize a function with useCallback and the containing value with useMemo. Treat these as targeted performance optimizations, not requirements for using Context.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Using Context for reducer-managed shared state

When shared state has more involved update logic, React demonstrates pairing useReducer with two contexts: one for the current state and one for the dispatch function. A provider component owns the reducer state; descendants can read state and dispatch actions without repeatedly passing them through intermediate components. Follow the pattern in React’s Scaling Up with Reducer and Context guide.

TypeScript: make a missing provider visible

In TypeScript, the value passed to createContext determines the inferred context type. If there is no sensible fallback, initialize the context with null and expose a custom consumer hook that checks for a missing provider and throws an error. After the check, the hook can return a non-null value to its callers. React documents this approach in Using TypeScript.

How function components differ from class components

Function components read context with the useContext Hook. Class components use static contextType and then read the value through this.context; the class API supports one context at a time. React describes the class API as equivalent to useContext for function components in its Component reference.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.