What is Context API?
The React Context API allows a React app to effectively produce global variables that can be passed around. It is a state management solution provided by React. Using it we can create what is known as a context and the context provides values like states and functions. It can be consumed by a group of components that are wrapped around the context.
To get started with Context API,
1. Create a Context.
import { createContext } from 'react';
export const AppContext = createContext(“”);
2. Create a Provider for the Context.
import { useState, React } from "react";
import { AppContext } from "./AppContext";
import AppComponent from "./AppComponent";
function App() {
const [text, setText] = useState("");
return (
<div>
<AppContext.Provider value={{ text, setText }}>
<AppComponent />
</AppContext.Provider>
</div>
);
}
export default App;
3. Using Context in React Component.
import { useContext } from 'react';
import { AppContext } from './AppContext';
function AppComponent() {
const { text, setText } = useContext(AppContext);
return (
<div>
<h1>{text}</h1>
<button onClick={() => setText('Geeks for Geeks')}>
Click me
</button>
</div>
);
}
export default AppComponent;
Components of Context API
There are two main components of React Context; Provider and Consumer.
- Provider – Providers are used to define and keep track of specific pieces of state. This component is responsible for providing the data that is shared across the components.
- Consumer – Consumers are responsible for modifying the state provided by the provider.
Advantages of Context API
- Data Sharing – Ease in data sharing is one of the major advantages of Context API. You can easily share data across components without having to pass the data through each level of the component tree. Thus, a global data flow is maintained while reducing bugs.
- Alternatives for Prop Drilling – Prop drilling occurs when a component needs to access data several levels deep into the component tree. This method becomes difficult and unmanageable with a large component tree. Thus, React Context API provides a mechanism to directly pass data across components without the need to pass down the props.
- Reduced Coupling – With an alternate provided to prop drilling, data can be passed across various components thus reducing coupling and dependence of components on one another making the application more efficient.
- Centralization – Using the global state flow, data can be stored centrally and updates on this data can be done more efficiently.
Limitations of Context API
- Low Performance – With large component trees, constant updates in context value can cause unnecessary re-renders and lower the performance of the application.
- Testing – Testing for context components is more difficult as compared to components with props-based state management. Providing correct context values during testing is a difficult task and requires additional initial setup.
- No Type-Safety – The context values are not type checked thus wrong values go undetected by the compiler and may lead to runtime errors.
Use Cases
Context API is a suitable choice when:
- You want to share data or state across different components of your application and need a centralized way to access and manage data.
- Your application has nested components. In this type of application, you can avoid prop drilling using Context API.
- The state of your application needs to be changed or updated dynamically.
- The components in your application that are required to have communication are not related to the component tree.
Which One to Use Context API or Redux in Your Next React Project
Using real-life examples, we can easily understand Which One to Use Context API or Redux in Your Next React Project. Consider a kitchen with a shopping list organizer. Take the case when using a Context API. It can be assumed as a common whiteboard in the kitchen where the shopping list is displayed and anyone can see it and change it. What if the shopping list organizer was Redux? When this list organizer is a redux it can be seen as an advanced version where all the people in the kitchen not only see the list but each update in the list can be tracked down to the person who made the changes. Thus, GraphQL can be considered as a list organizer that keeps track of each operation, and Context API is used for simpler tasks.
Therefore, in this article, we’ve explained the differences between Redux and Context API in a way that’s easy to understand, helping you grasp how they work differently in React apps.