Context API: First Look ๐
Jorjis Hasan
Posted on August 14, 2024
React's built-in Context API came to solve props drilling. Before using ContextAPI we had to pass data through multiple layers to reach the target point. It eliminates unnecessary steps for data flow.
Imagine you have a central place to store data. From anywhere in your app, you can read/write those data. And this is ContextAPI under the hood. Before walking into your imagination, let's eyeball some practical use cases using context API.
-
Theming:
- Applying consistent styling (like dark or light themes) across different components.
-
User Authentication:
- Managing and accessing authentication status and user data across various components.
-
Multi-language Support:
- Implementing internationalization to allow components to access and change the app's language.
You are 3 steps behind to say hi ๐ to contextAPI:
- (step 1) Create Context
- (step 2) Read/Consume Context
- (step 3) Write/Modify Context
โณ๏ธ Step 1: Create Context:
// UserContext.js
import { createContext } from "react";
const UserContext = createContext({
isLoggedIn: false,
});
export default UserContext;
Following the single responsibility principle , we make a separate UserContext.js
to create a new context. Then import the createContext
function.
We put an object with isLoggedIn
value inside the createContext
function and wrap it with a variable UserContext
. Don't forget to export ๐.
โณ๏ธ Step 2: Read/Consume Context:
Contact of Code: In body component, Show Login Status:
to true
if user is logged in else show false.
// Body.js
import { useContext } from "react";
import UserContext from "../context/UserContext";
const Body = () => {
const { isLoggedIn } = useContext(UserContext);
return <p>Login Status: {isLoggedIn ? "true" : "false"}</p>;
};
export default Body;
We import a hook useContext,
to consume/read data from the context. After destructuring isLoggedIn
value, do conditional rendering.
โณ๏ธ Step 3: Write/Modify Context:
Contact of Code: The header will have a login/logout
button. By clicking the button, the isLoggedIn
value will toggle from true
to false
and vice-versa, and the change must be reflected in the body component.
// Header.js
import { useContext } from "react";
import UserContext from "../context/UserContext";
export const Header = ({ setIsLoggedIn }) => {
const { isLoggedIn } = useContext(UserContext);
return (
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
{isLoggedIn ? "Logout" : "Login"}
</button>
);
};
export default Header;
// App.js
import "./App.css";
import Header from "./components/Header";
import Body from "./components/Body";
import { useContext, useState } from "react";
import UserContext from "./context/UserContext";
const App = () => {
const { isLoggedIn: defaultStatus } = useContext(UserContext);
const [isLoggedIn, setIsLoggedIn] = useState(defaultStatus);
return (
<UserContext.Provider value={{ isLoggedIn }}>
<Header setIsLoggedIn={setIsLoggedIn} />
<Body />
</UserContext.Provider>
);
};
export default App;
Entire BreakDown ๐
Header.js
- Imports context and defines the Header component, accepting setIsLoggedIn as a prop.
- Uses useContext(UserContext) to access isLoggedIn and toggles it via a button click.
- Renders the button with dynamic text ("Login" or "Logout") and exports the component.
App.js
- Retrieve Context Value: To avoid name conflict, rename the
isLoggedIn
variable todefaultLoginStatus
while destructure. - Initialize State: Create a new State variable with the renamed variable
(defaultLoginStatus)
from UserContext. - Provide Context: Wrap the
Header & Footer
components with Providing new value usingProvider
. - Pass State Setter: The Header component receives the
setIsLoggedIn
function as a prop. This allows Header to update theisLoggedIn
state, which will then be reflected in theUserContext
.
Let's Speed-Up the Article.
TL;DR:
-> Create context using createContext()
API.
-> Read the Context using useContext()
hooks.
-> Provide the Context to Header
and Body
by Provider
, modify context by a button from Header
.
Posted on August 14, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 22, 2024