React Context

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

  1. What is React Context?
  2. Creating and Using React Context
    • Example: Creating a Context
    • Example: Using Context in Class Components
    • Example: Using Context in Functional Components
  3. Updating Context
    • Example: Updating Context in Class Components
    • Example: Updating Context in Functional Components
  4. Using Context for Nested Components
    • Example: Nested Component with Context
  5. Key Features of React Context
  6. 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

  1. Create a New File for the Context: In the src directory, create a new file named MyContext.js.

  2. Define the Context: Add the following code to MyContext.js to create and export a context:

    // MyContext.js
    import React from 'react';
    
    const MyContext = React.createContext();
    
    export default MyContext;
    

Example: Using Context in Class Components

  1. Create a New File for the Component: In the src directory, create a new file named ClassComponent.js.

  2. Define the Component: Add the following code to ClassComponent.js to 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

  1. Create a New File for the Component: In the src directory, create a new file named FunctionalComponent.js.

  2. Define the Component: Add the following code to FunctionalComponent.js to 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

  1. Use the Context in App.js: Open src/App.js and modify the App component 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.Provider is used to provide a context value to the component tree.
    • ClassComponent and FunctionalComponent consume the context value and display it.

Updating Context

Example: Updating Context in Class Components

  1. Create a New File for the Component: In the src directory, create a new file named UpdateClassComponent.js.

  2. Define the Component: Add the following code to UpdateClassComponent.js to 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;
    
  3. Modify MyContext.js to Handle State: Update MyContext.js to 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

  1. Create a New File for the Component: In the src directory, create a new file named UpdateFunctionalComponent.js.

  2. Define the Component: Add the following code to UpdateFunctionalComponent.js to 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;
    
  3. Update App.js to Include New Components: Open src/App.js and modify the App component 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:

    • MyProvider is used to manage the context state and provide it to the component tree.
    • UpdateClassComponent and UpdateFunctionalComponent demonstrate how to update the context value.

Using Context for Nested Components

Example: Nested Component with Context

  1. Create a New File for the Component: In the src directory, create a new file named NestedComponent.js.

  2. Define the Component: Add the following code to NestedComponent.js to 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;
    
  3. Use the Nested Component in Another Component: Modify FunctionalComponent.js to include NestedComponent:

    // 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;
    
  4. Update App.js to Include New Components: Open src/App.js and modify the App component 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:

    • NestedComponent consumes the context value provided by

MyProvider.

  • FunctionalComponent includes NestedComponent to demonstrate nested context usage.

Key Features of React Context

  1. Global State Management: React Context allows you to manage global state that can be accessed by any component in the tree.
  2. Avoid Prop Drilling: Context helps to avoid prop drilling by providing a way to pass data through the component tree without manually passing props.
  3. Easy to Update: Context values can be easily updated, and the updates will be reflected across all components consuming the context.
  4. 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top