React's Context API allows you to share state (or values) across components without prop drilling. Prop drilling happens when you pass props through multiple nested components to get to a child. Imagine the following application where we use logged-in user info to display content:
import React, { render } from 'react';
function UserInfo({ user }: { user: User }) {
return <span>{user.name} / {user.uid}</span>
}
function UserPosts({ user }: { user?: User }) {
return <ul>
{user.posts.map(i => (
<li key={i.id}>{i.title}</li>
))}
</ul>
}
function UserDetails({ user }) {
return (
<>
<UserInfo user={user} />
<UserPosts user={user} />
</>
)
}
export default function App() {
const user = {
name: "Tomas",
uid: 1,
posts: [
{ id: 1, title: "Post 1" },
{ id: 2, title: "Post 2" },
]
}
return (
<UserDetails user={user} />
);
}
render(<App />)
Every time we want to use user in our application, we would have to provide the user as a prop of the child component. You can see that this can quickly become complicated. For example when you are dealing with themes or localisation you do not want to provide theme and language to every component. With Context API, you can avoid this by making data globally accessible to components that need it.
Provider
to wrap components that need access to the shared state.useContext
to access the shared values in a component.To make using Context simpler and reusable, we’ll create:
Before simplifying, here's the traditional way to use Context:
import React, { createContext, useState, useContext } from "react";
// Step 1: Create a Context
const UserContext = createContext();
// Step 2: Provide the Context
export const UserProvider = ({ children }) => {
const [user, setUser] = useState("John Doe");
return (
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider>
);
};
// Step 3: Consume the Context
const UserProfile = () => {
const { user, setUser } = useContext(UserContext);
return (
<div>
<h1>User: {user}</h1>
<button onClick={() => setUser("Jane Doe")}>Change User</button>
</div>
);
};
export default function App() {
return (
<UserProvider>
<UserProfile />
</UserProvider>
);
}
To avoid calling useContext(UserContext)
repeatedly, let’s create a custom hook.
We extract the consumption logic into a custom hook:
import React, { createContext, useState, useContext } from "react";
// Create a Context
const UserContext = createContext();
// Custom Hook to Access Context
export const useUser = () => {
const context = useContext(UserContext);
if (!context) {
throw new Error("useUser must be used within a UserProvider");
}
return context;
};
// Custom Provider Component
export const UserProvider = ({ children }) => {
const [user, setUser] = useState("John Doe");
return (
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider>
);
};
Here’s the cleaner way to consume the context:
import React from "react";
import { UserProvider, useUser } from "./UserContext";
// Consuming Context via Custom Hook
const UserProfile = () => {
const { user, setUser } = useUser();
return (
<div>
<h1>User: {user}</h1>
<button onClick={() => setUser("Jane Doe")}>Change User</button>
</div>
);
};
export default function App() {
return (
<UserProvider>
<UserProfile />
</UserProvider>
);
}
UserProvider
encapsulates the Provider
setup.useContext(UserContext)
.useUser
is called outside UserProvider
, it throws an error. This ensures proper usage.useContext
calls.createContext
to set up shared state.This approach is scalable, clean, and ideal for managing global state in React applications.
Let me know if you'd like another example or an advanced use case, like combining useReducer
with Context! 🚀
Let's take a look at a very convenient functionality in React, which allows you to share a common state or configuration across your whole app without passing values to each component.
React's Context API allows you to share state (or values) across components without prop drilling. Prop drilling happens when you pass props through multiple nested components to get to a child. Imagine the following application where we use logged-in user info to display content
For example, the information on your current user has to be passed to all the component that use the user ...
In our case, the UserDetails has to pass the user to UserInfo or UserPosts components. Imagine a much deeper nesting and the number of props you would have to pass. With Context API, you can avoid this by making data globally accessible to components that need it. Let's simplify our example.
First, let's import createContext and useContext from react.
Then, for type safety, we define the shape of data stored in the context. In our case, we will store a user property with user details.
Then, we create the context, using the createContext function and provide the default value. This value will be used in case you forget to wrap your component with the context provider. Let's do that now!
First, we initialise the user data ...
... and then we add the UserContext provider with the current user value. From now on, we can access the user value in any of the child components at any level of the hierarchy under the UserContext provider.
We access the value using the useContext hook, providing the type of the context we want to access. Note that we no longer need the user prop as we access the user from the context.
Similarly, we access the user from the context in the UserPosts component. Pretty handy right? Let's add some more functionality and simplify our example.
First thing we simplify is the use of the context with a custom hook.
With this custom hook, we no longer need to remember or import the type of the context. We can conveniently export it from a utility class and import it whenever needed.
Next, we will add the login and logout functionality, and add this function into our context, since login will replace the current user and logout will remove the user from the context.
This is our second simplification, where we create a custom component handling our User Context.
First, there is a user state variable holding the current user value.
Then, this component returns a UserContext provider with ...
... the current user or null if user is not logged in ...
... the login functionality, in our case just hard coding the current user.
... the logout functionality removing the current user
... and also making sure we render all children provided to this Context provider.
We also add a new login form that takes advantage of the new login and logout functions and renders either a login or logout button based on whether the user is logged in or out.
Last, we make sure to use our new UserProvider component with a new LoginForm child.
When we run this example, we can see that login in and out of the application works correctly, propagating the user value through context into all child components. This approach is scalable, clean, and ideal for managing global state in React applications.