Skip to main content
useContext is a React Hook that lets you read and subscribe to a context from your component.

Parameters

ReactContext<T>
required
The context object that you previously created with createContext. The context itself does not hold the information, it only represents the kind of information you can provide or read from components.
Pass the context itself (created by createContext), not Context.Consumer or Context.Provider.

Returns

useContext returns the context value for the calling component. It is determined as the value passed to the closest Context.Provider above the calling component in the tree. If there is no such provider, the returned value will be the defaultValue you passed to createContext for that context. The returned value is always up-to-date. React automatically re-renders components that read a context if the context value changes.

Usage

Passing data deeply into the tree

Call useContext at the top level of your component to read context:

Updating data passed via context

Often, you want the context to change over time. To update context, combine it with state:

Passing multiple values

You can pass any JavaScript value, including objects:
When passing objects as context values, be careful about creating new objects on every render. This will cause all consumers to re-render. Consider using useMemo:

Specifying a fallback default value

If React can’t find any providers of that particular context in the parent tree, the context value returned by useContext will be equal to the default value:

Overriding context for a part of the tree

You can override the context for a part of the tree by wrapping that part in a provider with a different value:

Common Patterns

Custom hook for context

Create a custom hook to make context usage more convenient:

Multiple contexts

You can use multiple contexts in the same component:

Context with reducer

Combine context with useReducer for more complex state management:

TypeScript

Troubleshooting

I can’t get a different value from my provider

Make sure you’re reading context inside a component that is a child of the provider:

I always get undefined from my context

You might be passing Context.Consumer instead of the context itself:

My component doesn’t re-render when context changes

Make sure the value you pass to the provider actually changes:

My context updates cause too many re-renders

Split your context into multiple contexts to avoid unnecessary re-renders:
Or use a state management library like Redux, Zustand, or Jotai for complex state.