Introduction
In this chapter, we will explore React Context, a powerful feature that allows you to share data across your component tree without passing props down manually at every level. React Context is useful for managing global state, such as user authentication, theme settings, and application settings.
Table of Contents
- What is React Context?
- Creating and Using React Context
- Example: Creating a Context
- Example: Using Context in Class Components
- Example: Using Context in Functional Components
- Updating Context
- Example: Updating Context in Class Components
- Example: Updating Context in Functional Components
- Using Context for Nested Components
- Example: Nested Component with Context
- Key Features of React Context
- Conclusion
What is React Context?
React Context provides a way to pass data through the component tree without having to pass props down manually at every level. This is useful for global data, such as the current authenticated user, theme, or application settings.
Creating and Using React Context
Example: Creating a Context
-
Create a New File for the Context: In the
srcdirectory, create a new file namedMyContext.js. -
Define the Context: Add the following code to
MyContext.jsto create and export a context:// MyContext.js import React from 'react'; const MyContext = React.createContext(); export default MyContext;
Example: Using Context in Class Components
-
Create a New File for the Component: In the
srcdirectory, create a new file namedClassComponent.js. -
Define the Component: Add the following code to
ClassComponent.jsto use the context:// ClassComponent.js import React, { Component } from 'react'; import MyContext from './MyContext'; class ClassComponent extends Component { render() { return ( <MyContext.Consumer> {(value) => ( <div> <h1>Class Component</h1> <p>Value from context: {value}</p> </div> )} </MyContext.Consumer> ); } } export default ClassComponent;
Example: Using Context in Functional Components
-
Create a New File for the Component: In the
srcdirectory, create a new file namedFunctionalComponent.js. -
Define the Component: Add the following code to
FunctionalComponent.jsto use the context:// FunctionalComponent.js import React, { useContext } from 'react'; import MyContext from './MyContext'; function FunctionalComponent() { const value = useContext(MyContext); return ( <div> <h1>Functional Component</h1> <p>Value from context: {value}</p> </div> ); } export default FunctionalComponent;
Example: Providing Context Value
-
Use the Context in
App.js: Opensrc/App.jsand modify theAppcomponent to provide a context value:// App.js import React from 'react'; import MyContext from './MyContext'; import ClassComponent from './ClassComponent'; import FunctionalComponent from './FunctionalComponent'; function App() { return ( <MyContext.Provider value="Hello from Context!"> <div> <ClassComponent /> <FunctionalComponent /> </div> </MyContext.Provider> ); } export default App;Explanation:
MyContext.Provideris used to provide a context value to the component tree.ClassComponentandFunctionalComponentconsume the context value and display it.
Updating Context
Example: Updating Context in Class Components
-
Create a New File for the Component: In the
srcdirectory, create a new file namedUpdateClassComponent.js. -
Define the Component: Add the following code to
UpdateClassComponent.jsto update the context value:// UpdateClassComponent.js import React, { Component } from 'react'; import MyContext from './MyContext'; class UpdateClassComponent extends Component { static contextType = MyContext; updateContext = () => { this.context.setValue('Updated value from Class Component'); }; render() { return ( <div> <h1>Update Class Component</h1> <p>Value from context: {this.context.value}</p> <button onClick={this.updateContext}>Update Context</button> </div> ); } } export default UpdateClassComponent; -
Modify
MyContext.jsto Handle State: UpdateMyContext.jsto include a provider with state management:// MyContext.js import React, { useState } from 'react'; const MyContext = React.createContext(); export const MyProvider = ({ children }) => { const [value, setValue] = useState('Initial context value'); return ( <MyContext.Provider value={{ value, setValue }}> {children} </MyContext.Provider> ); }; export default MyContext;
Example: Updating Context in Functional Components
-
Create a New File for the Component: In the
srcdirectory, create a new file namedUpdateFunctionalComponent.js. -
Define the Component: Add the following code to
UpdateFunctionalComponent.jsto update the context value:// UpdateFunctionalComponent.js import React, { useContext } from 'react'; import MyContext from './MyContext'; function UpdateFunctionalComponent() { const { value, setValue } = useContext(MyContext); const updateContext = () => { setValue('Updated value from Functional Component'); }; return ( <div> <h1>Update Functional Component</h1> <p>Value from context: {value}</p> <button onClick={updateContext}>Update Context</button> </div> ); } export default UpdateFunctionalComponent; -
Update
App.jsto Include New Components: Opensrc/App.jsand modify theAppcomponent to include the new components:// App.js import React from 'react'; import { MyProvider } from './MyContext'; import ClassComponent from './ClassComponent'; import FunctionalComponent from './FunctionalComponent'; import UpdateClassComponent from './UpdateClassComponent'; import UpdateFunctionalComponent from './UpdateFunctionalComponent'; function App() { return ( <MyProvider> <div> <ClassComponent /> <FunctionalComponent /> <UpdateClassComponent /> <UpdateFunctionalComponent /> </div> </MyProvider> ); } export default App;Explanation:
MyProvideris used to manage the context state and provide it to the component tree.UpdateClassComponentandUpdateFunctionalComponentdemonstrate how to update the context value.
Using Context for Nested Components
Example: Nested Component with Context
-
Create a New File for the Component: In the
srcdirectory, create a new file namedNestedComponent.js. -
Define the Component: Add the following code to
NestedComponent.jsto demonstrate using context in nested components:// NestedComponent.js import React from 'react'; import MyContext from './MyContext'; function NestedComponent() { return ( <MyContext.Consumer> {(value) => ( <div> <h2>Nested Component</h2> <p>Value from context: {value}</p> </div> )} </MyContext.Consumer> ); } export default NestedComponent; -
Use the Nested Component in Another Component: Modify
FunctionalComponent.jsto includeNestedComponent:// FunctionalComponent.js import React, { useContext } from 'react'; import MyContext from './MyContext'; import NestedComponent from './NestedComponent'; function FunctionalComponent() { const value = useContext(MyContext); return ( <div> <h1>Functional Component</h1> <p>Value from context: {value}</p> <NestedComponent /> </div> ); } export default FunctionalComponent; -
Update
App.jsto Include New Components: Opensrc/App.jsand modify theAppcomponent to include the new components:// App.js import React from 'react'; import { MyProvider } from './MyContext'; import ClassComponent from './ClassComponent'; import FunctionalComponent from './FunctionalComponent'; import UpdateClassComponent from './UpdateClassComponent'; import UpdateFunctionalComponent from './UpdateFunctionalComponent'; function App() { return ( <MyProvider> <div> <ClassComponent /> <FunctionalComponent /> <UpdateClassComponent /> <UpdateFunctionalComponent /> </div> </MyProvider> ); } export default App;Explanation:
NestedComponentconsumes the context value provided by
MyProvider.
FunctionalComponentincludesNestedComponentto demonstrate nested context usage.
Key Features of React Context
- Global State Management: React Context allows you to manage global state that can be accessed by any component in the tree.
- Avoid Prop Drilling: Context helps to avoid prop drilling by providing a way to pass data through the component tree without manually passing props.
- Easy to Update: Context values can be easily updated, and the updates will be reflected across all components consuming the context.
- Works with Class and Functional Components: React Context can be used with both class components and functional components, providing flexibility in how you structure your application.
Conclusion
In this chapter, you learned about React Context and how it allows you to share data across your component tree without passing props down manually at every level. We covered creating and using context, updating context, and using context for nested components. Understanding and using React Context can help you manage global state more efficiently in your React applications.