Search⌘ K
AI Features

Introducing the React Context

Explore the React context to understand how it enables sharing of data like user info and themes across components. Learn to create, provide, and consume context values, manage nested providers, and handle default context values when no provider is found.

React context data structure

The context is modeled with a ReactContext data type holding a _currentValue value, and it also contains a component provider.

 React context data structure
React context data structure

Creating and sharing context

We can create a context with the createContext function. For instance, if we want to share a piece of user information, we can create a UserContext and hold a defaultValue:

const UserContext = createContext(defaultValue)
export default UserContext

The created context can be shared via a JavaScript export statement, and this way, when any other file or component needs it, it can be imported.

The context allows us ...