Welcome to the Context Consumer lesson in React JS! In this tutorial, we will delve into one of the essential features of React that allows data to be passed between components without having to pass props down manually. Let's get started!
In a nutshell, the Context API allows you to create global variables that can be passed around in a React application without having to pass props down multiple levels. This can greatly simplify the management of state in complex applications.
In the Context API, the Consumer component is used to access the context value provided by a Context Provider. In this lesson, we will focus on how to use the Consumer component to access the context data.
Before we dive into the Consumer component, let's first create a Context Provider to provide some data that we can access using the Consumer.
import React from 'react';
const ThemeContext = React.createContext();
class ThemeProvider extends React.Component {
state = {
isDarkTheme: true,
};
toggleTheme = () => {
this.setState({ isDarkTheme: !this.state.isDarkTheme });
};
render() {
return (
<ThemeContext.Provider value={{ ...this.state, toggleTheme }}>
{this.props.children}
</ThemeContext.Provider>
);
}
}
export { ThemeContext, ThemeProvider };In this example, we created a ThemeContext and a ThemeProvider. The ThemeProvider has a state that keeps track of whether the dark theme is enabled or not. We also added a toggleTheme function to switch between the dark and light themes.
Now that we have our ThemeProvider, let's create a component that uses the ThemeContext to access the theme state and toggle it.
import React, { Component } from 'react';
import { ThemeContext } from './ThemeContext';
class ToggleThemeButton extends Component {
render() {
return (
<ThemeContext.Consumer>
{(context) => (
<button onClick={() => context.toggleTheme()}>
Toggle Theme
</button>
)}
</ThemeContext.Consumer>
);
}
}
export default ToggleThemeButton;In the above example, we used the ThemeContext.Consumer component to access the context value provided by the ThemeProvider. Inside the Consumer, we received the context object and called the toggleTheme function to switch between the dark and light themes.
š Note: The ThemeContext.Consumer should always be wrapped around the component that wants to access the context value.
Now let's see how we can use the ThemeProvider and ToggleThemeButton in a simple app.
import React from 'react';
import ThemeProvider from './ThemeContext';
import ToggleThemeButton from './ToggleThemeButton';
function App() {
return (
<ThemeProvider>
<div>
<h1>My App</h1>
<ToggleThemeButton />
</div>
</ThemeProvider>
);
}
export default App;In this example, we wrapped the entire app in the ThemeProvider and added a ToggleThemeButton to switch between the dark and light themes.
That's it for the Context Consumer lesson! In the next lesson, we will learn about Context.Consumer with Class Components. Until then, happy coding! š”