Context API

Introduction: The React Context API is like a special tool that helps different parts of a React app share information without a lot of manual work. Instead of passing messages (props) to each component individually, the Context API acts like a helpful organizer.
Lets Look at Context API definition
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
I know you feel little difficult to understand context API by definition. Let me explain through simple example
Example 1: The Magic Backpack
Let's imagine you have a magic backpack, and you are planning a trip to different places with your friends. Each friend has a favorite item they like to have on the trip - one friend loves a particular snack, another friend loves a specific game, and so on. Now, instead of asking each friend individually what they want in the backpack, you use the Context API. The Context API is like a magical assistant who helps you organize the backpack for the entire trip. You tell the Context API what each friend's favorite item is, and the Context API makes sure that when you reach a new destination, the right items are easily accessible for each friend. So, when you arrive at the beach, the friend who loves snacks can quickly find their favorite snack because the Context API has organized the backpack in a way that makes it easy for everyone to get what they need. In the same way, in computer programming, the Context API helps different parts of a program communicate and share important information without directly talking to each other. It acts as an organizer, making sure that the right information is available to the right parts of the program when they need it.
Example 2: The Magical Referee
Imagine you're playing a game with your friends, and each friend has a special ability. The Context API is like a magical referee who helps everyone know what special ability each friend has. Instead of each friend shouting their ability every time they want to use it, they just tell the referee once. The referee remembers and makes sure that everyone knows what abilities are available. So, when you're playing, you can easily ask the referee, "Hey, what cool thing can my friend do again?" and the referee will remind you without everyone having to keep repeating it. In computer programs, the Context API is a bit like that magical referee. It helps different parts of the program share important information without always talking directly to each other. It keeps things organized so that everyone can easily access the information they need.
Context API usually use in almost every projects of REACT specially when you are dealing with the servers. They are use for state management. So now we understand what is Context-API now lets move towards the implementation part
Using Context in Your React Project - Part 1: Setting Up Context
Step 1: Create React App Start by creating a new React app.
Step 2: Create UserContext.js Inside a special folder called Context_api
, create a file named UserContext.js
with this code:
import React from 'react'; const UserContext = React.createContext(); export default UserContext;
Now you wrote your Context is it done?
No!!! we have further more to deal.remember examples that we discuss at the start of the blog. Yes about the MagicBackpack and Magical Refree, they both are our source providers. Source providers means they are providing us all the necessary information that we need for us.
So do we need same provider for our project ?
Definitely yes.Step 3: Create UserContextProvider.jsx In the same folder, create a file named
UserContextProvider.jsx
with this code .Jsx because we are using it for wrapping the components in the single one like our example of backpack. In backpack example and we have all the necessary things in magicBackPack same like that in this we are wrapping all the necessary components in our ProviderUserContextProvider.jsx
import React from 'react'; import UserContext from "UserContext"; const UserContextProvider = ({child}) => { const [user,setUser] = React.useState(null); return( <UserContext.Provider value={user,setUser}> {child} </UserContext.Provider> ) } export default UserContextProvider;
In code snippets we imported the UserContext that we made in previous file
Now make the function called UserContextProvider and pass the child(it refers to data) in it. So why we pass the child in it the, main reason for this is we need to access of child element in all over the project.
as we discuss we are wrapping those data like MagicBagPack.
Have you notice the </UserContext.Provider> taking value props. It is taking the access to the data. suppose you have more values that you want to give as context-data you add in this value props.this was our Part 1 in this we created basic structure of Context-API.
Using Context in Your React Project - Part 2: Putting It All Together
Now we have our
contextUser
andcontextUserProvider
. Lets see how to use it.Step 1: Use UserContextProvider in App.jsx In your
App.jsx
file, importUserContextProvider
and wrap your components with it:import React from "react"; import UserContextProvider from "./context/UserContextProvider"; const App = () => { return ( <UserContextProvider> <h1>this is where we add our components</h1> </UserContextProvider> ); }; export default App;
so in this file we imported our UserContextProvider and now we are going to add the components that we need to accessible in our project.
Let's create two components Login.jsx and Profile.jsx in components folder
|-- components
| |-- Login
| | |-- Login.jsx
| |-- Profile
| | |-- Profile.jsx
|-- App.jsx
|-- main.js
We have to send and receive information in our Provider we created two files Login and Profile in Login we will send the information and in Profile we will take the information
Step 2: Create Login.jsx and Profile.jsx Inside a components
folder, create two files named Login.jsx
and Profile.jsx
.
import React, { useState, useContext } from "react";
import UserContext from "../context/UserContext";
function Login() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
//using below line we are sending login info to the ContextProvider
const { setUser } = useContext(UserContext);
const handleSubmit = (e) => {
e.preventDefault();
setUser({ username, password });
};
return (
<div>
<h2>Login</h2>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="username"
/>{" "}
<input
type="text"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="password"
/>
<button onClick={handleSubmit}>Submit</button>
</div>
);
}
export default Login;
In above code we imported the useContext.
We know that we have props in the UserContextProvider called value {user,setUser} Now we just set the user info using setUser for the UserContextProvider
Lets type below code in the Profile.jsx for the data reciving which we send using in the Login.
import React, { useContext } from "react";
import UserContext from "../context/UserContext";
function Profile() {
const { user } = useContext(UserContext);
if (!user) return <div>please login</div>;
return <div>Welcome {user.username}</div>;
}
export default Profile;
In above code we imported useContext from the react and now we are just checking if user information is send by user is display or not . If msg Welcome user.name
then information is send otherwise just display please Login.
We are just showing the user information by using UserContextProvider's user props as we mentioned it in the value props.
The React Context API is like a helpful tool for beginners in coding. It makes it easier for different parts of your app to talk to each other. The examples and steps provided here should help you understand and use the Context API in your React projects. If you have any questions, feel free to ask!
If you found this helpful or have suggestions for improvement, let me know!
Subscribe to my newsletter
Read articles from Chaitanya Katore directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Chaitanya Katore
Chaitanya Katore
I'm Chaitanya Katore! I specialize in building robust solutions across frontend and backend .with hands-on experience from internships, I’ve participated in various open-source hackathons, contributing to impactful projects and learning through collaboration. Now, as an SDE 1 at UST, I continue my journey of coding, problem-solving, and leaving a positive mark on the tech community. Let's connect and build the future together!