Using the React Context API for Efficient State Management
Last Updated :
13 Aug, 2024
The React Context API is a robust feature announced in React 16.3. It offers a way to share data within components without passing props directly at all stages. This is specifically useful for global data that many components seek to access, like user authentication, theme, or language settings. Rather than prop drilling, Context enables you to create a shared data layer that can be accessed by any component to its extent.
Using the React Context API for Efficient State ManagementWhen to Use Context API
The Context API is optimal when:
- Global State Management: Use Context API for operating global state in small to medium-sized applications where using more complex state management libraries like Redux might be overwhelming.
- User Authentication: Context API is best for handling user authentication status (logged in/logged out) and user information over varied components without prop drilling.
- Current User Data: When you require providing user-specific data (e.g., user profile, preferences) to multiple components in your app, Context API can help ignore passing props down multiple levels.
- Notification System: Implementing a notification system where notifications need to be shown across varied parts of the application can be optimally controlled with the Context API.
Creating a Context
To create a context, you use the createContext() method. This method returns an object with Provider and Consumer components.
//Creating a context
import React from 'react';
const MyContext = React.createContext();
export default MyContext;
Providing the Context
To provide a value to the Context, wrap the components that need access to the value with the Provider component:
// Providing the context value
function App()
{
return
(
<MyContext.Provider value={{ value, setValue }}>
{/* Components that can access the context value */}
</MyContext.Provider>
);
}
export default App;
Consuming the Context
To consume the Context value in a component, use the useContext hook:
//Consuming the Context
function AnotherComponent()
{
const contextValue = React.useContext(MyContext);
//contextValue contains the shared value
}
Using Context with Class Components
To use context in class components, use the static contextType or Context.Consumer.
// Using Context with Class Components
class MyClassComponent extends Component
{
static contextType = MyContext;
render()
{
const { value } = this.context;
return <div>{value}</div>;
}
}
export default MyClassComponent;
Updating Context
To update context values, pass a function through the context and call it from the consuming components.
// Updating Context
function NewComponent()
{
const { value, updateValue } = useContext(MyContext);
return
(
<div>
<div>{value}</div>
<button onClick={updateValue}>Update Value</button>
</div>
);
}
export default NewComponent;
Best Practices
- Do not use context too much as it can slow down your app.
- Only use it for data that desires to be shared everywhere.
- In place of one big context, create multiple smaller ones for varied data.
- Set up default values for your context to verify it works although a Provider is hidden.
- Keep your context logic sorted by putting it into custom hooks or helper functions.
- Try not to update context values too often to escape slowing down your app.
Example Project: Counter Application
Let us create an easy counter application that shows the use of the React Context API.
Step 1: First, create a new React project using create-react-app .
npx create-react-app counter-application
Step 2: Navigate to the root directory of project using the following command.
cd counter-application
Project Structure:
Project structurepackage.json
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Step 3: Understand the logic
- In src/contexts/CounterContext.js create the context utilizing React.createContext.
- In src/contexts/CounterProvider.js use useState to control the count state and pass both the count and setCount function to the context value.
- In the App component, we wrap our component tree with the CounterProvider to offer the context to all nested components.
Example: This example shows the use of React Context API.
JavaScript
// src/contexts/CounterContext.js
import React from 'react';
const CounterContext = React.createContext();
export default CounterContext;
JavaScript
// src/contexts/CounterProvider.js
import React, { useState } from 'react';
import CounterContext from './CounterContext';
const CounterProvider = ({ children }) => {
const [count, setCount] = useState(0);
return (
<CounterContext.Provider value={{ count, setCount }}>
{children}
</CounterContext.Provider>
);
};
export default CounterProvider;
JavaScript
// src/components/CounterDisplay.js
import React, { useContext } from 'react';
import CounterContext from '../contexts/CounterContext';
const CounterDisplay = () => {
const { count } = useContext(CounterContext);
return <div>Current Count: {count}</div>;
};
export default CounterDisplay;
JavaScript
// src/components/CounterButton.js
import React, { Component } from 'react';
import CounterContext from '../contexts/CounterContext';
class CounterButton extends Component {
render() {
return (
<CounterContext.Consumer>
{({ setCount }) => (
<button onClick={() => setCount(prevCount => prevCount + 1)}>
Increment
</button>
)}
</CounterContext.Consumer>
);
}
}
export default CounterButton;
JavaScript
// src/components/CounterControls.js
import React, { useContext } from 'react';
import CounterContext from '../contexts/CounterContext';
const CounterControls = () => {
const { setCount } = useContext(CounterContext);
return (
<div>
<button onClick={() => setCount(prevCount => prevCount + 1)}>Increment</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>Decrement</button>
</div>
);
};
export default CounterControls;
JavaScript
//src/App.js
import React from 'react';
import CounterProvider from './contexts/CounterProvider';
import CounterDisplay from './components/CounterDisplay';
import CounterControls from './components/CounterControls';
const App = () => {
return (
<CounterProvider>
<CounterDisplay />
<CounterControls />
</CounterProvider>
);
};
export default App;
JavaScript
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
Run your application using the following command.
npm start
Output:
OutputTroubleshooting and Common Issues
- Context Not Updating: Verify you are using a state updater function like setState to update context values.
- Context Value Undefined: Confirm the component consuming the context is wrapped within the Provider.
- Re-Renders: Escape updating context values too often. Use memoization techniques if required.
- Default Values Not Working: Double-check that you have allocated default values when creating the context.
Conclusion
Using the React Context API in your projects enables for organized state management by giving a way to share data over the component tree without prop drilling. By creating a context, defining a provider, and consuming the context, you can organize state handling and intensify the scalability of your application.
Similar Reads
GeeksforGeeks Practice - Leading Online Coding Platform GeeksforGeeks Practice is an online coding platform designed to help developers and students practice coding online and sharpen their programming skills with the following features. GfG 160: This consists of 160 most popular interview problems organized topic wise and difficulty with with well writt
6 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
7 Different Ways to Take a Screenshot in Windows 10 Quick Preview to Take Screenshot on Windows 10:-Use the CTRL + PRT SC Keys to take a quick screenshot.Use ALT + PRT SC Keys to take a Screenshot of any application window.Use Windows + Shift + S Keys to access the Xbox Game Bar.Use Snip & Sketch Application as well to take screenshotTaking Scree
7 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read