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
- Setting Up a New React Project
- Syntax of
useContext - Real-Time Project: Employee Management System with Theme Context
- Project Setup
- Creating the Theme Context
- Creating the Employee Component
- Using
useContextto Access the Theme - Toggling the Theme
- Conclusion
Setting Up a New React Project
First, let’s create a new React project using the create-react-app tool.
-
Open your terminal and run the following command:
npx create-react-app usecontext-employee-app -
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 usingReact.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
useContexthook is used to access the value ofMyContext. - The
valuevariable contains the context value, which can be used within the component.
Real-Time Project: Employee Management System with Theme Context
Project Setup
-
Open the project directory in your code editor.
-
Remove the default content from
src/App.jsandsrc/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
-
Create a new file named
ThemeContext.jsin thesrcdirectory. -
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:
ThemeContextis created usingReact.createContext.- The
ThemeProvidercomponent manages thethemestate and provides thethemevalue andtoggleThemefunction to the component tree.
Creating the Employee Component
-
Create a new file named
Employee.jsin thesrcdirectory. -
Define the
Employeecomponent:// 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
useContexthook is used to access thethemevalue andtoggleThemefunction from theThemeContext. - The
toggleThemebutton toggles between light and dark themes.
- The
-
Create a CSS file named
Employee.cssto 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
-
Access Context Values: The
useContexthook is used to access thethemevalue andtoggleThemefunction from theThemeContext.const { theme, toggleTheme } = useContext(ThemeContext); -
Toggle Theme: The
toggleThemebutton toggles the theme between light and dark.<button className="btn btn-secondary mb-3" onClick={toggleTheme}> Toggle Theme </button> -
Apply Theme Classes: The theme class (
lightordark) 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.