React useState Hook

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

  1. Setting Up a New React Project
  2. Syntax of useState
  3. 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
  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 employee-management-app
    
  2. 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 useState hook initializes the count state to 0.
  • The setCount function is used to update the count state.
  • Clicking the button increments the count by 1.

Real-Time Project: Employee Management System

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';
    
    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

  1. Create a new file named Employee.js in the src directory.
  2. Define the Employee component:
    // 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;
    
  3. Create a CSS file named Employee.css to 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

  1. Initialize State: We use the useState hook to manage the list of employees and the input values.
    const [employees, setEmployees] = useState([]);
    const [inputValue, setInputValue] = useState({ id: '', firstName: '', lastName: '', email: '' });
    
  2. Handle Adding Employees: The handleAddEmployee function 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: '' });
      }
    };
    
  3. Handle Deleting Employees: The handleDeleteEmployee function removes an employee from the list.
    const handleDeleteEmployee = (index) => {
      setEmployees(employees.filter((_, i) => i !== index));
    };
    

Adding New Employees

  1. Form Submission: The form submission is handled by the handleAddEmployee function, 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

  1. Map through Employees: The employees array 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

  1. Delete Button: Each employee item has a delete button that calls the handleDeleteEmployee function 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.

Leave a Comment

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

Scroll to Top