-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

Learn React with TypeScript
By :

In this section, we will learn about a feature in React called context. We will then refactor the app from the last section to use React context.
React context is an object that can be accessed by components. This object can contain state values, so it provides a mechanism for sharing state across components.
A context is created using a createContext
function as follows:
const Context = createContext<ContextType>(defaultValue);
A default value for the context must be passed into createContext
. It also has a generic type parameter for the type that represents the object created by createContext
.
A context provider component needs to be placed in the component tree above the components requiring access to it. A provider wrapper component can be created that stores the shared state and passes it to the context component as follows:
export function Provider({ children }: Props) { const [someState, setSomeState...