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. F…


This content originally appeared on DEV Community and was authored by Jorjis Hasan

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;

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 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.


This content originally appeared on DEV Community and was authored by Jorjis Hasan


Print Share Comment Cite Upload Translate Updates
APA

Jorjis Hasan | Sciencx (2024-08-14T14:47:08+00:00) Context API: First Look 👀. Retrieved from https://www.scien.cx/2024/08/14/context-api-first-look-%f0%9f%91%80/

MLA
" » Context API: First Look 👀." Jorjis Hasan | Sciencx - Wednesday August 14, 2024, https://www.scien.cx/2024/08/14/context-api-first-look-%f0%9f%91%80/
HARVARD
Jorjis Hasan | Sciencx Wednesday August 14, 2024 » Context API: First Look 👀., viewed ,<https://www.scien.cx/2024/08/14/context-api-first-look-%f0%9f%91%80/>
VANCOUVER
Jorjis Hasan | Sciencx - » Context API: First Look 👀. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/08/14/context-api-first-look-%f0%9f%91%80/
CHICAGO
" » Context API: First Look 👀." Jorjis Hasan | Sciencx - Accessed . https://www.scien.cx/2024/08/14/context-api-first-look-%f0%9f%91%80/
IEEE
" » Context API: First Look 👀." Jorjis Hasan | Sciencx [Online]. Available: https://www.scien.cx/2024/08/14/context-api-first-look-%f0%9f%91%80/. [Accessed: ]
rf:citation
» Context API: First Look 👀 | Jorjis Hasan | Sciencx | https://www.scien.cx/2024/08/14/context-api-first-look-%f0%9f%91%80/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.