Certain information in your application needs to be available to multiple components, including those nested deep in the UI tree. However, passing data through layers of components via props can quickly become tedious and difficult to maintain as the application grows.
To simplify data management, context allows us to define information in the parent component, and they will be automatically accessible to all the components down the tree.
Creating the context
To get started with context, navigate to the contexts
directory, and create a new file called UserContext.jsx
. This file will define the user context and allow different components to access user data.
1src
2├── App.jsx
3├── assets
4├── components
5├── contexts
6│ └── UserContext.jsx <=====
7└── main.jsx
Inside UserContext.jsx
, initialize the context using the createContext()
function. TIt can be initialized with or without a default value.
contexts/UserContext.jsx
1import { createContext } from "react";
2
3// Without a default value
4export const UserContext = createContext({});
1import { createContext } from "react";
2
3// With default value
4export const UserContext = createContext({
5 username: "John Doe",
6 email: "johndoe@example.com",
7 status: "active",
8});