Context API: First Look ๐Ÿ‘€

jorjishasan

Jorjis Hasan

Posted on August 14, 2024

Context API: First Look ๐Ÿ‘€

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.

  1. Theming:
    • Applying consistent styling (like dark or light themes) across different components.
  2. User Authentication:
    • Managing and accessing authentication status and user data across various components.
  3. 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;

Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode
// 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;
Enter fullscreen mode Exit fullscreen mode

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 to defaultLoginStatus 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 using Provider.
  • Pass State Setter: The Header component receives the setIsLoggedIn function as a prop. This allows Header to update the isLoggedIn state, which will then be reflected in the UserContext.

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.

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
jorjishasan
Jorjis Hasan

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

ยฉ TheLazy.dev

About