• Latest
  • Trending
An Introduction to the React Context API

An Introduction to the React Context API

April 1, 2022
Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025
ATC Ghana supports Girls-In-ICT Program

ATC Ghana supports Girls-In-ICT Program

April 25, 2023
Vice President Dr. Bawumia inaugurates  ICT Hub

Vice President Dr. Bawumia inaugurates ICT Hub

April 2, 2023
Co-Creation Hub’s edtech accelerator puts $15M towards African startups

Co-Creation Hub’s edtech accelerator puts $15M towards African startups

February 20, 2023
Data Leak Hits Thousands of NHS Workers

Data Leak Hits Thousands of NHS Workers

February 20, 2023
EU Cybersecurity Agency Warns Against Chinese APTs

EU Cybersecurity Agency Warns Against Chinese APTs

February 20, 2023
How Your Storage System Will Still Be Viable in 5 Years’ Time?

How Your Storage System Will Still Be Viable in 5 Years’ Time?

February 20, 2023
The Broken Promises From Cybersecurity Vendors

Cloud Infrastructure Used By WIP26 For Espionage Attacks on Telcos

February 20, 2023
Instagram and Facebook to get paid-for verification

Instagram and Facebook to get paid-for verification

February 20, 2023
YouTube CEO Susan Wojcicki steps down after nine years

YouTube CEO Susan Wojcicki steps down after nine years

February 20, 2023
Inaugural AfCFTA Conference on Women and Youth in Trade

Inaugural AfCFTA Conference on Women and Youth in Trade

September 6, 2022
  • Consumer Watch
  • Kids Page
  • Directory
  • Events
  • Reviews
Friday, 17 July, 2026
  • Login
itechnewsonline.com
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion
Subscription
Advertise
No Result
View All Result
itechnewsonline.com
No Result
View All Result

An Introduction to the React Context API

by ITECHNEWS
April 1, 2022
in Data Science, Leading Stories
0 0
0
An Introduction to the React Context API

The React Context API is a state management tool used for sharing data across React components. Find out how to use the Context API to keep track of authenticated users in functional components.

What Is the React Context API?

React is a component-based library. Its applications comprise different components that work together. In some cases, your application needs to share data across these components.

YOU MAY ALSO LIKE

French Telco Orange Hit by Cyber-Attack

ATC Ghana supports Girls-In-ICT Program

For instance, you might want to share the username of the current user from the Logincomponent to other components in your application. Context makes it easier to share the username by eliminating the need to pass data through each component in the component tree.

When Should You Use the React Context API?

Before using React context, first, consider the type of data you are working with. Context is more suited for static data. Data that changes continuously will cause too many re-renders and as a result, reduce performance. The data should also be global or at least used by many components, for instance, data such as user language, themes, and authentication.

Using Context to Keep Track of User Authentication Status

If your application uses authentication, many of its components will need to know the current user’s authentication state. Passing down the authentication status to each component is redundant and leads to prop drilling so using context is a good option.

createContext()

To get started with the Context API, you first have to create it using this syntax.

const Context = React.createContext(defaultValue);

The default value is unnecessary and is usually used for testing purposes.

Provider

Each context has a provider that receives a value consumed by the components it wraps. It allows these components to subscribe to context changes.

<Context.Provider value={/* some value */}>

useContext

useContext() is a React hook that allows components to consume context. You only need to pass in the context.

const contextValue = useContext(Context)

Let’s now create the authentication context to keep track of the authentication state.

Start by creating a new file, AuthContext.js, and add the following.

import { createContext } from "react";
const AuthContext = createContext();
export default AuthContext;

Next, create AuthProvider.js and add the provider function.

import { useState, useEffect } from 'react';
import { getUser } from './auth.js'
import AuthContext from './AuthContext'
export const AuthProvider = ({ children }) => {
 const [user, setUser] = useState(null);
 useEffect(() => {
 const currentUser = getUser()
 setUser(currentUser)
 }, []);
 
 return (
 <AuthContext.Provider value={{ user }}>{children}</AuthContext.Provider>
 );
 };

Here, you are retrieving the current user from a fake getUser() function. In a real application, this would be your backend service.

Store the user in the current state to keep track of any changes then pass the user to the provider in the value prop.

AuthProvider.js also receives the children with access to the context.

The next step is to create a custom hook that will allow components wrapped with the provider to access context.

Create a new file useAuthContext.js and add the following.

import AuthContext from "./AuthContext";
const useAuthContext.js = () => {
 const user = useContext(AuthContext);
 if (user === undefined) {
 throw new Error("useAuthContext can only be used inside AuthProvider");
 }
 return user;
};

Now if code outside the provider calls AuthContext, your application will handle the error gracefully.

The final step is to wrap the components using context with AuthProvider.js.

import { AuthProvider } from "./AuthContext";
ReactDOM.render(
 <React.StrictMode>
 <AuthProvider>
 <App />
 </AuthProvider>
 </React.StrictMode>,
 rootElement
);

Here is an example of how you would use context to protect a page from unauthenticated users.

import useAuthContext from "./useAuthContext";
import { Navigate } from "react-router-dom";
const Profile = () => {
 const { user } = useAuthContext();
 if (!user) {
 return <Navigate replace to="/login" />;
 }
 return (
 <>
 <h1>Profile</h1>
 </>
 );
};

This component conditionally renders the profile page depending on the authentication status of the user. It checks if the user exists and if they don’t, redirects them to the login page. Otherwise, it renders the profile page.

When Not to Use React Context API

In this article, you learned how to use Context to keep track of an authenticated user across components. While you might be tempted to use Context for all of your data sharing use cases, you shouldn’t as it reduces code maintainability and performance. Every time the context value changes each component that consumes state re-renders. If the data is only used by a few components, opt for props.

Source: makeuseof
Via: MARY GATHONI
Tags: An Introduction to the React Context API
ShareTweet

Get real time update about this post categories directly on your device, subscribe now.

Unsubscribe

Search

No Result
View All Result

Recent News

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025
ATC Ghana supports Girls-In-ICT Program

ATC Ghana supports Girls-In-ICT Program

April 25, 2023

About What We Do

itechnewsonline.com

We bring you the best Premium Tech News.

Recent News With Image

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025

Recent News

  • Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa July 29, 2025
  • French Telco Orange Hit by Cyber-Attack July 29, 2025
  • ATC Ghana supports Girls-In-ICT Program April 25, 2023
  • Vice President Dr. Bawumia inaugurates ICT Hub April 2, 2023
  • Home
  • InfoSec
  • Opinion
  • Africa Tech
  • Data Storage

© Copyright 2026, All Rights Reserved | iTechNewsOnline.Com - Powered by BackUPDataSystems

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In

Add New Playlist

No Result
View All Result
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion

© Copyright 2026, All Rights Reserved | iTechNewsOnline.Com - Powered by BackUPDataSystems

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?
Go to mobile version