React.js / React Context and Global State
Consuming Context in Functional and Class Components
In this tutorial, we will learn how to consume context in both functional and class components in React. We'll also compare the different ways of consuming context in these two ty…
Section overview
5 resourcesCovers using React Context API to manage global state and avoid prop drilling.
1. Introduction
In this tutorial, we will explore how to consume context in React using both functional and class components.
By the end of this tutorial, you will be able to:
- Understand what context is and how to use it
- Consume context in functional components using the useContext hook
- Consume context in class components using the Context.Consumer component
Prerequisites:
- Basic understanding of React
- Knowledge of JavaScript ES6 syntax
- Familiarity with both functional and class components in React
2. Step-by-Step Guide
Context provides a way to pass data through the component tree without having to pass props down manually at every level. In other words, it's a more efficient way to share values between components.
In functional components, we use the useContext Hook to consume context, whereas in class components, we use the Context.Consumer component.
Functional Components
The useContext Hook accepts a context object (the value returned from React.createContext) and returns the current context value, as given by the nearest context Provider up the tree from this component.
Example:
import React, { useContext } from 'react';
import MyContext from './MyContext';
function MyComponent() {
const contextValue = useContext(MyContext);
return <div>{contextValue}</div>;
}
In this example, MyComponent uses the useContext hook to consume the context value from MyContext.
Class Components
In class components, we can consume context using the <Context.Consumer> component. This lets you subscribe to a context within a function component.
Example:
import React from 'react';
import MyContext from './MyContext';
class MyComponent extends React.Component {
render() {
return (
<MyContext.Consumer>
{contextValue => <div>{contextValue}</div>}
</MyContext.Consumer>
);
}
}
In this example, MyComponent is a class component that uses the MyContext.Consumer component to consume the context value.
3. Code Examples
Functional Component Example
import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button theme={theme}>I am styled by theme context!</button>;
}
In this example, the useContext hook is used to consume the ThemeContext. The value of the context is then used as a prop for the button component.
Class Component Example
import React from 'react';
const ThemeContext = React.createContext('light');
class ThemedButton extends React.Component {
render() {
return (
<ThemeContext.Consumer>
{theme => <button theme={theme}>I am styled by theme context!</button>}
</ThemeContext.Consumer>
);
}
}
In this example, ThemeContext.Consumer is used to consume the ThemeContext. The value of the context is then used as a prop for the button component.
4. Summary
In this tutorial, we've learned how to consume context in functional and class components in React. We learned that functional components use the useContext hook, while class components use the Context.Consumer component.
The next step in your learning could be understanding when to use context and when to use state or props in your components.
5. Practice Exercises
- Create a context and consume it in a functional component.
- Create a context and consume it in a class component.
- Create a context with multiple values and consume it in a functional component.
Solutions and explanations will be provided after you've attempted these exercises.
Remember, practice is key to mastering any concept. Keep experimenting with different scenarios and use cases.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article