Introduction
The Context API in React allows components to share data with each other, even if they are not directly related. It helps avoid the problem of passing data through many components by letting components access shared data directly. It helps in preventing the prop drilling problem.
Consider the diagram to represent a chain of components. If we want to pass the data from parent to child B, we must pass it through components between them, even though they don’t require this data. This situation is called prop drilling. Your code may become more difficult to understand, maintain, and refactor because of prop drilling.
Context API can help in this situation. The top level of your component tree can store data and make it available for any other component that needs it, avoiding prop drilling.
What is the Context API?
The Context API in React allows components to access shared data without passing props through multiple levels of the component tree. The Context API revolves around the concept of a “context” object, which can be created using the createContext function.
Consider the diagram to represent how the Context API works. If we want to pass the data from parent to child B, we can directly pass this data without passing through an intermediate component.
How to use the Context API:
Step 1:
Create a Context: To create a context, use the createContext function provided by React. This function returns a context object that consists of a Provider and a Consumer.
//Create a new context
import { createContext } from ‘react’;
export const AuthContext = createContext();
In this example, we create an AuthContext using createContext(), which will hold the authentication state and related functions.
Step 2:
Provide the Context: wrap the relevant part of your component tree with the AuthContext.Provider component. This allows the child components to access the Context.
The Provider component is critical to the Context API. It accepts a “value” prop containing the shared data, and any Provider child component can access this shared data. To ensure that all child components in your application may access the shared data, wrap the Provider component around the top-level component.
import { useState, React } from “react”;
import { AuthContext } from “./component/AuthContext”;
import {HomePage, DashboardPage} from “./component/Home”;
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const login = () => {
setIsLoggedIn(true);
};
const logout = () => {
setIsLoggedIn(false);
};
// Provide the context value
const authContextValue = {
isLoggedIn,
login,
logout,
};
return (
// Wrap the component tree with the Provider
<AuthContext.Provider value={authContextValue}>
<HomePage />
<DashboardPage />
</AuthContext.Provider>
);
}
export default App;
The App component acts as the provider and manages the isLoggedIn state. It provides the login and logout functions to update the authentication state. The context value is provided using the value prop of AuthContext.Provider. We wrap the HomePage and DashboardPage components to make the authentication context available to these components.
Step 3:
Consume the Context: In any component that needs access to the Context, use the component or the useContext hook to consume the Context and retrieve the data.
import { useContext } from “react”;
import { AuthContext } from “./AuthContext”;
//Create a custom hook to consume the context
const useAuth = () => useContext(AuthContext);
export const HomePage = () => {
const { isLoggedIn, login, logout } = useAuth();
return (
<div>
{isLoggedIn ? (
<div>
<h2>Welcome, User!</h2>
<button onClick={logout}>Logout</button>
</div>
) : (
<div>
<h2>Please log in</h2>
<button onClick={login}>Login</button>
</div>
)}
</div>
);
};
export const DashboardPage = () => {
const { isLoggedIn } = useAuth();
return (
<div>
{isLoggedIn ? (
<h2>Dashboard Page</h2>
) : (
<h2>Access denied. Please log in.</h2>
)}
</div>
);
};
The useAuth custom hook is used to consume the Context in the HomePage and DashboardPage components. The HomePage component displays a welcome message and a logout button if the user is logged in or a login button if the user is not logged in. The DashboardPagecomponent shows a dashboard page if the user is logged in or an access denied message if the user is not logged in.
Conclusion:
The Context API in React provides an efficient solution for state management and data sharing between components. With the Provider and Consumer components, you can establish a global state accessible throughout the component tree. This eliminates the need for excessive prop drilling and simplifies state management. Embrace the Context API to streamline state management, enhance code maintainability, and improve your React application.
Leave A Comment