React useContext Hook

Introduction

In this chapter, we will explore the useContext hook in React. This hook allows you to access context values in functional components, providing a simple way to manage global state. We will create a new React project from scratch, explain the syntax of useContext, and walk through a real-time project step by step to demonstrate its usage.

Table of Contents

  1. Setting Up a New React Project
  2. Syntax of useContext
  3. Real-Time Project: Employee Management System with Theme Context
    • Project Setup
    • Creating the Theme Context
    • Creating the Employee Component
    • Using useContext to Access the Theme
    • Toggling the Theme
  4. Conclusion

Setting Up a New React Project

First, let’s create a new React project using the create-react-app tool.

  1. Open your terminal and run the following command:

    npx create-react-app usecontext-employee-app
    
  2. Navigate to the project directory:

    cd usecontext-employee-app
    

Syntax of useContext

The useContext hook allows you to access context values in functional components. It simplifies the process of consuming context compared to the Context.Consumer component.

Syntax

const value = useContext(MyContext);
  • MyContext: The context object you created using React.createContext.

Example

import React, { useContext } from 'react';
import MyContext from './MyContext';

function MyComponent() {
  const value = useContext(MyContext);

  return <div>{value}</div>;
}

export default MyComponent;

Explanation:

  • The useContext hook is used to access the value of MyContext.
  • The value variable contains the context value, which can be used within the component.

Real-Time Project: Employee Management System with Theme Context

Project Setup

  1. Open the project directory in your code editor.

  2. Remove the default content from src/App.js and src/App.css:

    // src/App.js
    import React from 'react';
    import './App.css';
    import Employee from './Employee';
    import { ThemeProvider } from './ThemeContext';
    
    function App() {
      return (
        <ThemeProvider>
          <div className="App">
            <h1>Employee Management System</h1>
            <Employee />
          </div>
        </ThemeProvider>
      );
    }
    
    export default App;
    
    /* src/App.css */
    .App {
      text-align: center;
      padding: 20px;
    }
    
    h1 {
      margin-bottom: 20px;
    }
    

Creating the Theme Context

  1. Create a new file named ThemeContext.js in the src directory.

  2. Define the ThemeContext:

    // src/ThemeContext.js
    import React, { createContext, useState } from 'react';
    
    const ThemeContext = createContext();
    
    export const ThemeProvider = ({ children }) => {
      const [theme, setTheme] = useState('light');
    
      const toggleTheme = () => {
        setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
      };
    
      return (
        <ThemeContext.Provider value={{ theme, toggleTheme }}>
          {children}
        </ThemeContext.Provider>
      );
    };
    
    export default ThemeContext;
    

    Explanation:

    • ThemeContext is created using React.createContext.
    • The ThemeProvider component manages the theme state and provides the theme value and toggleTheme function to the component tree.

Creating the Employee Component

  1. Create a new file named Employee.js in the src directory.

  2. Define the Employee component:

    // src/Employee.js
    import React, { useContext } from 'react';
    import ThemeContext from './ThemeContext';
    import './Employee.css';
    
    function Employee() {
      const { theme, toggleTheme } = useContext(ThemeContext);
    
      return (
        <div className={`container mt-5 ${theme}`}>
          <h2>Employee List</h2>
          <button className="btn btn-secondary mb-3" onClick={toggleTheme}>
            Toggle Theme
          </button>
          <ul className="list-group">
            <li className="list-group-item">1 - John Doe (john@example.com)</li>
            <li className="list-group-item">2 - Jane Smith (jane@example.com)</li>
          </ul>
        </div>
      );
    }
    
    export default Employee;
    

    Explanation:

    • The useContext hook is used to access the theme value and toggleTheme function from the ThemeContext.
    • The toggleTheme button toggles between light and dark themes.
  3. Create a CSS file named Employee.css to style the Employee component:

    /* src/Employee.css */
    .container {
      max-width: 600px;
      margin: 0 auto;
      text-align: left;
    }
    
    .list-group-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;
      border: 1px solid #ccc;
      border-radius: 4px;
      margin-bottom: 10px;
    }
    
    .light {
      background-color: #f8f9fa;
      color: #343a40;
    }
    
    .dark {
      background-color: #343a40;
      color: #f8f9fa;
    }
    
    button {
      padding: 10px 20px;
      border: none;
      border-radius: 4px;
      background-color: #007bff;
      color: white;
      cursor: pointer;
    }
    
    button:hover {
      background-color: #0056b3;
    }
    
    .btn-secondary {
      background-color: #6c757d;
    }
    
    .btn-secondary:hover {
      background-color: #5a6268;
    }
    

Using useContext to Access the Theme

  1. Access Context Values: The useContext hook is used to access the theme value and toggleTheme function from the ThemeContext.

    const { theme, toggleTheme } = useContext(ThemeContext);
    
  2. Toggle Theme: The toggleTheme button toggles the theme between light and dark.

    <button className="btn btn-secondary mb-3" onClick={toggleTheme}>
      Toggle Theme
    </button>
    
  3. Apply Theme Classes: The theme class (light or dark) is applied to the container div based on the current theme.

    <div className={`container mt-5 ${theme}`}>
    

Conclusion

In this chapter, we created a new React project and explored the useContext hook. We learned the syntax of useContext and walked through a real-time project step by step to create an Employee Management System application with theme context. By understanding and using the useContext hook, you can easily manage and consume context values in your functional components, making your React applications more dynamic and interactive.

Leave a Comment

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

Scroll to Top