Context Hooks
Context allows a component to receive information from distant parents without prop driling.
useContext
reads and subscribes to a context.
useContext
useContext
is a React Hook that lets you read and subscribe to context from your component.
Parameters
- The context that you’ve 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 SomeContext.Provider above the calling component in the tree. If there is no such provider, then the returned value will be the defaultValue you have passed to createContext for that context. The returned value is always up-to-date. React automatically re-renders components that read some context if it changes.
Caveats
-
useContext()
call in a component is not affected by providers returned from the same component. The corresponding<Context.Provider>
needs to be above the component doing the useContext() call. -
React automatically re-renders all the children that use a particular context starting from the provider that receives a different value. Skipping re-renders with memo does not prevent the children receiving fresh context values.
-
memo
will not prevent the component from re-rendering if you only have ituseContext()
inside the component and the value is changed.
All components that hold same context will re-renders if only one property is changed.
Example: basic
Example: complext component
Example: context with reducer
Example: Optimizing re-renders when passing objects and functions
Whenever MyApp re-renders (for example, on a route update), this will be a different object pointing at a different function, so React will also have to re-render all components deep in the tree that call useContext(AuthContext).
There is no need to re-render if currentUser has not changed. So you need to wrap the login function with useCallback and wrap the object creation into useMemo.