In this blog post, we’ll explore React’s Context API and delve into its usage. The Context API is widely employed as a state management tool and is frequently considered as an alternative to Redux.
As per the React documentation:
“Context provides a way to pass data through the component tree without having to pass props down manually at every level.”
To elaborate, this feature enables you to make certain values accessible to all components within your application, irrespective of the complexity of your component tree.
This capability can significantly enhance the efficiency of your application by eliminating the need to pass down props manually through multiple levels of components. It simplifies the process of sharing data among components, offering a more streamlined and manageable approach to state management. In this blog, we will extensively discuss context API for state management.
When to use context
const App = () => {
return(
<ParentClass color= "blue"/>
);
}
const ParentClass = (props) => (
<ChildClass color= {props.color} />
)
const ChildClass = (props) => (
<GrandChildClass color= {props.color} />
)
const GrandChildClass = (props) => (
<p>Color: {props.color}</p>
)
Code language: JavaScript (javascript)
In the given code, the application employs the ‘color’ prop in the ParentClass and passes it down through each subsequent component without considering whether each component actually requires it. This approach becomes unwieldy, especially when dealing with deeply nested components like GrandChildClass. The difficulty of managing props in such cases is a challenge that can be addressed by using React Context API. This API is specifically designed for sharing values that can be deemed “global,” such as preferred language, current user, or theme.
By utilizing context, the need for prop drilling can be alleviated. To implement this solution, create a dedicated context component that can be utilized across the application. Following the project initialization, establish a file named ColorContext.js in the /src folder.
State Management With Context API
The Context API in React simplifies state management by enabling the sharing of data across components without prop drilling. It eliminates the need to pass state through numerous layers, enhancing code clarity and maintainability. Developers create a context with createContext
and access it using the useContext
hook, allowing components to efficiently retrieve global state. This approach fosters a cleaner and more scalable architecture, particularly beneficial in larger applications where centralized state management is crucial. The Context API streamlines development, making it easier to manage and access shared data throughout the component hierarchy.
Create Context
By utilizing React.createContext, we can establish a context and specify any value as an argument for React.createContext. In our instance, we’re assigning the color “white” to signify a light theme.
This process results in the creation of two components: ColorContext.Provider and ColorContext.Consumer. Their roles are straightforward:
– Provider: The component responsible for supplying the value.
– Consumer: A component that consumes the provided value.
Here’s an example implementation:
import React from "react";
const ColorContext = React.createContext("white");
export default ColorContext;
Code language: JavaScript (javascript)
To utilize this context across various components, the Provider must be employed. According to the React documentation, every context object includes a Provider React component that enables consuming components to subscribe to changes in context.
React Context Provider
Upon successfully establishing the context, we can import the context and employ it to generate our provider. To ensure access to the context throughout the entire application, it’s necessary to encase our app within the ColorContext.Provider.
import ColorContext from './ColorContext';
function App() {
const color= "white";
return (
<ColorContext.Provider value = {color}>
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to my web page</h1>
</header>
</div>
</ColorContext.Provider>
);
}
Code language: JavaScript (javascript)
Consuming the context
Utilizing Context in React components involves a consistent approach for providing context, but consumption methods vary between class components and functional components with hooks.
Context API with class components
The Context API in React facilitates state management across components, including class components. Through the createContext
and Consumer
components, data can be shared globally. While hooks are more common with functional components, class components can utilize the Context.Consumer
pattern to access and update shared state.
Accessing Context in Class Components:
In class components, the prevalent method involves using `static contextType`. The context value can then be accessed through `this.context`, available in various lifecycle methods.
import React, { Component } from 'react';
import ColorContext from './ColorContext';
class Page extends Component {
static contextType = ColorContext;
componentDidMount() {
const colorValue = this.context;
console.log(colorValue); // "white"
}
render() {
const colorValue = this.context;
return <div>Color Value is {colorValue}</div>;
}
}
Code language: JavaScript (javascript)
Traditional Approach with Consumer:
An alternative method involves wrapping the component in a `ColorContext.Consumer` to access context values as props.
import React, { Component } from 'react';
import { ColorContext } from './ColorContext';
class Page extends Component {
render() {
return (
<ColorContext.Consumer>
{colorValue => <div>{colorValue}</div>}
</ColorContext.Consumer>
);
}
}
Code language: JavaScript (javascript)
Context api functional component and Hooks
In React, the Context API, combined with functional components and hooks like useContext
, provides an elegant solution for managing global state. This approach streamlines state sharing without class components, promoting a modern and concise development paradigm in React applications.
Using useContext:
For functional components, the `useContext` hook provides a straightforward equivalent to `static contextType`.
import React, { useContext } from 'react';
import ColorContext from './ColorContext';
export const HomePage = () => {
const colorValue = useContext(ColorContext);
return <div>{colorValue}</div>;
}
Code language: JavaScript (javascript)
createContext and useContext are some context api hooks example.
React createcontext
To update the context, maintain a wrapper class containing the context state and a method for updating it. The example below shows a file named ColorContext.js:
Context api example
import React, { Component } from 'react';
const ColorContext = React.createContext();
class ColorContextProvider extends Component {
state = {
color: ""
}
setColor = (color) => {
this.setState({ color });
}
render() {
const { children } = this.props;
const { color } = this.state;
return (
<ColorContext.Provider value={{ color, setColor }}>
{children}
</ColorContext.Provider>
);
}
}
export default ColorContext;
export { ColorContextProvider };
To apply context updates in a component:
import React, { Component } from 'react';
import ColorContext from './ColorContext';
class Page extends Component {
static contextType = ColorContext;
render() {
const { color, setColor } = this.context;
return (
<div>
<button
onClick={() => {
const newColorValue = "black";
setColor(newColorValue);
}}
>
Update Color
</button>
<p>{`Current Color Value: ${color}`}</p>
</div>
);
}
}
Code language: JavaScript (javascript)
While Context offers a simpler alternative to Redux with minimal code, be mindful of the potential issue where everything consuming the context re-renders when the context state changes. This can lead to excessive re-renders if the context is widely used or serves as the sole state manager for the entire app.