Skip to main content
useContext returns the current context value for the given context. The value is determined by the nearest <Context.Provider> above the calling component in the tree.

Signature

Parameters

PreactContext<T>
required
The context object created by createContext. The hook reads the current value from the nearest provider for this context.

Returns

Returns the current context value of type T. The value is determined by the value prop of the nearest <Context.Provider> above the calling component. If there is no provider, the default value passed to createContext is returned.

Basic Usage

Multiple Contexts

With TypeScript

Updating Context Value

Authentication Context

Complex State in Context

When the value prop of the nearest <Context.Provider> updates, all components that call useContext with that context will re-render, even if their parent would normally prevent re-rendering.
The context value is always taken from the nearest provider above the component. Context does not “tunnel” through intermediate components.
If there is no provider for a context above the component, useContext returns the default value that was passed to createContext.