Introduction
In this chapter, we will explore the useState hook in React. This hook allows you to add state to functional components. We will create a new React project from scratch, explain the syntax of useState, and walk through a real-time project step by step to demonstrate its usage. Our project will be an Employee Management System app, where we manage employee details such as ID, first name, last name, and email.
Table of Contents
- Setting Up a New React Project
- Syntax of
useState - Real-Time Project: Employee Management System
- Project Setup
- Creating the Employee Component
- Adding State to Manage Employees
- Adding New Employees
- Displaying the List of Employees
- Deleting Employees
- 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 employee-management-app - Navigate to the project directory:
cd employee-management-app
Syntax of useState
The useState hook lets you add state to functional components. It returns an array with two elements: the current state value and a function to update that state.
Syntax
const [state, setState] = useState(initialState);
state: The current state value.setState: A function to update the state.initialState: The initial value of the state.
Example
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Current Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
Explanation:
- The
useStatehook initializes thecountstate to0. - The
setCountfunction is used to update thecountstate. - Clicking the button increments the count by 1.
Real-Time Project: Employee Management System
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'; function App() { return ( <div className="App"> <h1>Employee Management System</h1> <Employee /> </div> ); } export default App;/* src/App.css */ .App { text-align: center; padding: 20px; } h1 { margin-bottom: 20px; }
Creating the Employee Component
- Create a new file named
Employee.jsin thesrcdirectory. - Define the
Employeecomponent:// src/Employee.js import React, { useState } from 'react'; import './Employee.css'; function Employee() { const [employees, setEmployees] = useState([]); const [inputValue, setInputValue] = useState({ id: '', firstName: '', lastName: '', email: '' }); const handleAddEmployee = (event) => { event.preventDefault(); if (inputValue.id && inputValue.firstName && inputValue.lastName && inputValue.email) { setEmployees([...employees, inputValue]); setInputValue({ id: '', firstName: '', lastName: '', email: '' }); } }; const handleDeleteEmployee = (index) => { setEmployees(employees.filter((_, i) => i !== index)); }; return ( <div className="container mt-5"> <form onSubmit={handleAddEmployee}> <div className="mb-3"> <input type="text" className="form-control" value={inputValue.id} onChange={(e) => setInputValue({ ...inputValue, id: e.target.value })} placeholder="ID" /> </div> <div className="mb-3"> <input type="text" className="form-control" value={inputValue.firstName} onChange={(e) => setInputValue({ ...inputValue, firstName: e.target.value })} placeholder="First Name" /> </div> <div className="mb-3"> <input type="text" className="form-control" value={inputValue.lastName} onChange={(e) => setInputValue({ ...inputValue, lastName: e.target.value })} placeholder="Last Name" /> </div> <div className="mb-3"> <input type="email" className="form-control" value={inputValue.email} onChange={(e) => setInputValue({ ...inputValue, email: e.target.value })} placeholder="Email" /> </div> <button type="submit" className="btn btn-primary">Add Employee</button> </form> <ul className="list-group mt-3"> {employees.map((employee, index) => ( <li key={index} className="list-group-item d-flex justify-content-between align-items-center"> {employee.id} - {employee.firstName} {employee.lastName} ({employee.email}) <button className="btn btn-danger btn-sm" onClick={() => handleDeleteEmployee(index)}>Delete</button> </li> ))} </ul> </div> ); } export default Employee; - Create a CSS file named
Employee.cssto style the Employee component:/* src/Employee.css */ form { margin-bottom: 20px; } input { padding: 10px; margin-right: 10px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 4px; } button { padding: 10px 20px; border: none; border-radius: 4px; background-color: #007bff; color: white; cursor: pointer; } button:hover { background-color: #0056b3; } ul { list-style-type: none; padding: 0; } li { padding: 10px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 4px; display: flex; justify-content: space-between; align-items: center; } li button { background-color: #dc3545; } li button:hover { background-color: #c82333; }
Adding State to Manage Employees
- Initialize State: We use the
useStatehook to manage the list of employees and the input values.const [employees, setEmployees] = useState([]); const [inputValue, setInputValue] = useState({ id: '', firstName: '', lastName: '', email: '' }); - Handle Adding Employees: The
handleAddEmployeefunction adds a new employee to the list if the input values are not empty.const handleAddEmployee = (event) => { event.preventDefault(); if (inputValue.id && inputValue.firstName && inputValue.lastName && inputValue.email) { setEmployees([...employees, inputValue]); setInputValue({ id: '', firstName: '', lastName: '', email: '' }); } }; - Handle Deleting Employees: The
handleDeleteEmployeefunction removes an employee from the list.const handleDeleteEmployee = (index) => { setEmployees(employees.filter((_, i) => i !== index)); };
Adding New Employees
- Form Submission: The form submission is handled by the
handleAddEmployeefunction, which prevents the default form submission, checks if the input values are not empty, adds the new employee to the list, and clears the input fields.<form onSubmit={handleAddEmployee}> <div className="mb-3"> <input type="text" className="form-control" value={inputValue.id} onChange={(e) => setInputValue({ ...inputValue, id: e.target.value })} placeholder="ID" /> </div> <div className="mb-3"> <input type="text" className="form-control" value={inputValue.firstName} onChange={(e) => setInputValue({ ...inputValue, firstName: e.target.value })} placeholder="First Name" /> </div> <div className="mb-3"> <input type="text" className="form-control" value={inputValue.lastName} onChange={(e) => setInputValue({ ...inputValue, lastName: e.target.value })} placeholder="Last Name" /> </div> <div className="mb-3"> <input type="email" className="form-control" value={inputValue.email} onChange={(e) => setInputValue({ ...inputValue, email: e.target.value })} placeholder="Email" /> </div> <button type="submit" className="btn btn-primary">Add Employee</button> </form>
Displaying the List of Employees
- Map through Employees: The
employeesarray is mapped to display each employee in an unordered list (<ul>).<ul className="list-group mt-3"> {employees.map((employee, index) => ( <li key={index} className="list-group-item d-flex justify-content-between align-items-center"> {employee.id} - {employee.firstName} {employee.lastName} ({employee.email}) <button className="btn btn-danger btn-sm" onClick={() => handleDeleteEmployee(index)}>Delete</button> </li> ))} </ul>
Deleting Employees
- Delete Button: Each employee item has a delete button that calls the
handleDeleteEmployeefunction with the index of the employee to be deleted.<button className="btn btn-danger btn-sm" onClick={() => handleDeleteEmployee(index)}>Delete</button>
Conclusion
In this chapter, we created a new React project and explored the useState hook. We learned the syntax of useState and walked through a real-time project step by step to create an Employee Management System application. By understanding and using the useState hook, you can manage state effectively in your functional components, making your React applications more dynamic and interactive.