useContext is a React Hook that lets you read and subscribe to a context from your component.
Parameters
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.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
CalluseContext 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:Specifying a fallback default value
If React can’t find any providers of that particular context in the parent tree, the context value returned byuseContext 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 withuseReducer 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 passingContext.Consumer instead of the context itself: