What is Context API?
The Context API is a React feature that allows you to share state across multiple components without having to pass props down manually at every level. Itβs like a global variable that all components in a tree can access but in a more efficient and easy way.
Let's first understand the key terms before moving on to the example. If you don't fully grasp the concepts right away, don't worry. Proceeding to the example will help clarify how everything works together.
Key Concepts of the Context API
Context Creation: Using createContext
to create a context object.
Provider: Using Context.Provider
to pass the state to child components.
Consumer: Using useContext
to access the state in any component.
To help you understand the Context API in a practical way, we'll build a very basic login page. In this example, when you type your name and submit it, you'll be greeted with your name. This simple example focuses on the Context API without the complexity of a larger application. I have also explained the code lines in the comments.
I will provide the names of all the files to make it easy for you to follow along. You can create these files in your src directory and check the functionality yourself.
Setting Up the Context
UserContext.js
First, we create a context. This context will hold the user data.
import React, { createContext } from 'react';
const UserContext = createContext();
export default UserContext;
UserContextProvider.jsx
Next, we create a provider component. This component will wrap around parts of our app that need access to the user data.
import React, { useState } from 'react';
import UserContext from './UserContext';
const UserContextProvider = ({ children }) => {
const [user, setUser] = useState(null);
return (
// whatever values you will give below,
//will be shared to anyone who will call them using useContext()
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider>
);
}
export default UserContextProvider;
Using the Context in Our App
App.jsx
In our main App component, we wrap the relevant parts of our app with the UserContextProvider.
import React from 'react';
import UserContextProvider from './UserContextProvider';
import Login from './Login.jsx';
import Profile from './Profile.jsx';
function App() {
return (
// This wrapping let's every children compenent to have the access
// to values using the useContext hook
<UserContextProvider>
<h1>Context Tutorial</h1>
<Login />
<Profile />
</UserContextProvider>
);
}
export default App;
Login.jsx
In the Login component, we use the useContext hook to access and update the user data.
import React, { useState, useContext } from 'react';
import UserContext from './UserContext';
function Login() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const { setUser } = useContext(UserContext);
// Here, we extract the setUser function from the UserContext using the useContext hook.
// Remember, we passed the user and setUser values in the UserContext.Provider:
// <UserContext.Provider value={{ user, setUser }}>, which makes them accessible to any component
// that uses the useContext hook with 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='password'
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder='password'
/>
<button onClick={handleSubmit}>Submit</button>
</div>
);
}
export default Login;
Profile.jsx
In the Profile component, we use the useContext hook to access the user data.
import React, { useContext } from 'react';
import UserContext from './UserContext';
function Profile() {
const { user } = useContext(UserContext);
if (!user) return <div>Login above to have your name here</div>;
return <div>Hello {user.username}</div>;
}
export default Profile;
You will see this interface when you run your React App using the above files.
After you enter a username and password(anything as there are no checks), this page will greet you with that username.
Here is the Summary of Context API
This image and the one at the very top is form a youtube video by Code Bootcamp.Feel free to ask questions in the comments. I'll be happy to answer them. Happy coding!
Top comments (1)
Interesting topic! Everything is explained articulately and clearly. For your project, consider checking out this free npm package: select-paginated.