Tuesday, 3 December 2024

Parent-Child State Management Example: User Information Management App in React

In this post, we are going to create a simple React application to manage user information. Each user has three properties: an id, a name, and an age. The application will display a list of users with options to edit and delete their details.

 

When an admin clicks the edit button next to a user, the button will change to a save button, allowing the admin to save any changes made. The edit and delete buttons will return after saving.

 

Additionally, there will be a form at the top of the page where the admin can enter new user details and add them to the existing list.

 

The focus of this post is to demonstrate how a child component (User) can update the state of its parent component (UsersInfo), allowing us to efficiently manage user data and interactions within our application.

 

Follow below step-by-step procedure to build the working application.

 

Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘child-update-parent-state’.

 

Project structure looks like below.

 


Step 2: Create components folder in src/ folder and define User and UsersInfo component.

 

User.jsx

import { useState } from "react";

export default function User({ user, setUsersInfo }) {
  const [editEnabled, setEditEnabled] = useState(true);
  const [userInfo, setUserInfo] = useState(user);

  return (
    <>
      <h1>User Details</h1>
      {editEnabled && (
        <ul>
          <li>id : {userInfo.id}</li>
          <li>username : {userInfo.name}</li>
          <li>age : {userInfo.age}</li>
        </ul>
      )}

      {!editEnabled && (
        <div>
          <p>
            <label htmlFor="id">ID : </label>
            <input id="id" type="text" value={userInfo.id} disabled />
          </p>
          <p>
            <label htmlFor="username">Username : </label>
            <input
              type="text"
              id="username"
              value={userInfo.name}
              onChange={(event) => {
                setUserInfo((currentUser) => ({
                  ...currentUser,
                  name: event.target.value,
                }));
              }}
            />
          </p>
          <p>
            <label htmlFor="age">Age : </label>
            <input
              type="text"
              id="age"
              value={userInfo.age}
              onChange={(event) => {
                setUserInfo((currentUser) => ({
                  ...currentUser,
                  age: Number(event.target.value), // Ensure age is treated as a number
                }));
              }}
            />
          </p>
          <br /> <br />
          <button
            onClick={() => {
              setUsersInfo((currentUsers) =>
                currentUsers.map((currentUser) => {
                  if (currentUser.id === userInfo.id) {
                    return {
                      ...currentUser,
                      name: userInfo.name,
                      age: userInfo.age,
                    };
                  }
                  return currentUser;
                })
              );
              setEditEnabled(true);
            }}
          >
            Save
          </button>
        </div>
      )}

      {editEnabled && (
        <div>
          <button
            onClick={() => {
              setEditEnabled(false);
            }}
          >
            Edit
          </button>
          &nbsp;
          <button
            onClick={() => {
              setUsersInfo((currentUsers) =>
                currentUsers.filter(
                  (currentUser) => currentUser.id !== userInfo.id
                )
              );
            }}
          >
            Delete
          </button>
        </div>
      )}
    </>
  );
}

UsersInfo.jsx

import User from "./User";
import { useState } from "react";

export default function UserList({ users }) {
  const [usersInfo, setUsersInfo] = useState(users);
  const [username, setUsername] = useState("");
  const [age, setAge] = useState("");

  return (
    <>
      <form
        onSubmit={(event) => {
          event.preventDefault();
          // Validate the input fields before adding a user
          if (!username || !age) {
            alert("Username and Age are required!");
            return;
          }
          if (isNaN(age)) {
            alert("Age must be a number");
            return;
          }

          if (age < 18 && age > 60) {
            alert("Age must be in between 18 and 60");
          }

          setUsersInfo((currentUsers) => {
            const newId = currentUsers.length + 1;
            return [
              ...currentUsers,
              { id: newId, name: username, age: Number(age) }, // Ensure age is a number
            ];
          });
          // Clear input fields after user is added
          setUsername("");
          setAge("");
        }}
      >
        <label htmlFor="username">Username : </label>
        <input
          type="text"
          id="username"
          value={username}
          onChange={(event) => {
            setUsername(event.target.value);
          }}
        />
        &nbsp;
        <label htmlFor="age">Age : </label>
        <input
          type="text"
          id="age"
          value={age}
          onChange={(event) => {
            setAge(event.target.value);
          }}
        />
        &nbsp;
        <button type="submit">Add User</button>
      </form>

      {usersInfo.map((user) => (
        <div key={user.id}>
          <User user={user} setUsersInfo={setUsersInfo} />
        </div>
      ))}
    </>
  );
}

Above code demonstrates a React application where users can be managed using edit, delete, and add functionalities. The application is structured into two components.

1.   User Component (User.jsx)

2.   UsersInfo Component (UsersInfo.jsx)

 

1. User Component (User.jsx)

This component is responsible for displaying the details of a single user, along with buttons to edit or delete that user. It also allows the admin to save any changes made.

 

State Management

1.   editEnabled: A boolean state that toggles between viewing and editing mode for a user.

2.   userInfo: Stores the current user's data (id, name, and age). It starts with the data passed as props from the parent component.

 

UI Logic

1.   When editEnabled is true, the user's details (id, name, age) are displayed in read-only mode.

2.   When editEnabled is false, editable input fields appear, allowing the user to update their details.

3.   The save button updates the user's information in the parent component's state using the setUsersInfo function passed from the parent. This ensures changes are reflected globally.

 

Event Handlers

1.   Edit Button: Switches the form to editing mode.

2.   Delete Button: Removes the current user from the list by calling setUsersInfo to filter out the user with the matching ID.

3.   Save Button: Saves the changes made by the user to the parent state (UsersInfo) by mapping over the current users and updating the relevant user’s data.

 

2. UsersInfo Component (UsersInfo.jsx)

This component manages the entire list of users and provides a form to add new users. It also renders individual User components for each user in the list.

 

State Management

1.   usersInfo: Stores the list of all users, initialized with the data passed from the users prop.

2.   username and age: Input fields for adding a new user.

 

Form Handling

At the top of the component, there is a form where the admin can enter a new username and age. When the form is submitted.

1.   Input validation ensures the fields are not empty, age is a number, and the age falls between 18 and 60.

2.   If valid, the new user is added to the usersInfo array with a new ID.

3.   After adding a user, the form fields are cleared for convenience.

 

Rendering User Components

For each user in the usersInfo array, the User component is rendered. The setUsersInfo function is passed as a prop to enable child components to update the parent component’s state.

 

Step 3: Update main.jsx like below.

 

main.jsx

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import UsersInfo from "./components/UsersInfo";

let users = [
  {
    id: 1,
    name: "Krishna",
    age: 36,
  },
  {
    id: 2,
    name: "Ram",
    email: "ram@abc.com",
    age: 37,
  },
];

createRoot(document.getElementById("root")).render(
  <StrictMode>
    <UsersInfo users={users} />
  </StrictMode>
);


Step 4: Build and run the Application by executing below commands.

  cd child-update-parent-state
  npm install
  npm run dev

You will see below kind of screen.



Try to experiment with the interaction provided in the above user interface to understand the application better.

You can download this application from this link.

Previous                                                    Next                                                    Home

Arrow functions in Javascript

Arrow functions provide a shorter syntax for writing functions. They are always anonymous, and you can omit the function keyword.

arrowFunction.js

let add = (a, b) => {
	return a + b;
};

let a = 5;
let b = 3;
let sum = add(5, 3);

console.log(`Sum of ${a} and ${b} is ${sum}`);

Output

Sum of 5 and 3 is 8

The code uses an arrow function, denoted by =>, which is a shorthand way to write a function expression in JavaScript.

 

If the function body contains only one expression, you can omit the curly braces and the return keyword.

let add = (a, b) => a + b;

arrowFunctionSingleExpression.js

let add = (a, b) => a + b;

let a = 5;
let b = 3;
let sum = add(5, 3);

console.log(`Sum of ${a} and ${b} is ${sum}`);

Output

Sum of 5 and 3 is 8

  

Previous                                                    Next                                                    Home

Text Decoration in CSS: A Beginner Guide to enhance Your Web Typography

The text-decoration property in CSS is used to add various visual decorations to text, such as underlining, overlining, strikethrough, or even a combination of these. It's a shorthand property that allows you to set multiple text-decoration-related properties in one go.

 

Properties of text-decoration

1. text-decoration-line: Specifies what kind of line decoration you want to apply to the text. The possible values are:

 

·      underline: Adds a line beneath the text.

·      overline: Adds a line above the text.

·      line-through: Adds a line through the text (strikethrough).

·      none: Removes any text decoration.

 

 

2. text-decoration-style: Defines the style of the text decoration. The possible values are:

 

·      solid: A solid line.

·      double: A double line.

·      dotted: A dotted line.

·      dashed: A dashed line.

·      wavy: A wavy line.

 

text-decoration-color: Specifies the color of the text decoration (underline, overline, or line-through). It can take any valid CSS color value.

 

text-decoration-thickness: Controls the thickness of the text decoration line. It can take values such as auto, from-font, or a length value (e.g., 2px).

 

Example

text-decoration: underline dotted red 2px;

 

textDecoration.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Text Decoration Order Example</title>
    <style>
        .underline {
            text-decoration: underline;
        }

        .overline {
            text-decoration: overline;
        }

        .line-through {
            text-decoration: line-through;
        }

        .custom-decoration {
            text-decoration: underline wavy red 6px;
        }

        p{
            font-size: 2em;
        }
    </style>
</head>
<body>
    <p>
        This is an example of <span class="underline">underlined text</span>,
        <span class="overline">overlined text</span>,
        and <span class="line-through">strikethrough text</span>.
    </p>
    <p>
        Here is a more customized decoration: 
        <span class="custom-decoration">wavy, red, 6px thick underline</span>.
    </p>
</body>
</html>

 


 

When using the text-decoration shorthand property, it's best to follow the recommended order of text-decoration-line, text-decoration-style, text-decoration-color, and text-decoration-thickness for clarity and to avoid potential issues. This way, you can create clear, visually appealing text decorations in your CSS.

  

Previous                                                    Next                                                    Home

Define a Navigation Section using nav element

The <nav> element in HTML is used to define a navigation section on a webpage. It's a semantic HTML5 element designed to enclose navigation links, making it clear to both users and search engines that this part of the page is dedicated to navigation.

The <nav> element groups the links together that navigate to different parts of the website or to other related sites. It helps to improve the structure and accessibility of your webpage. Using <nav> helps screen readers and other assistive technologies to understand that the enclosed links are for navigation purposes.

 

It’s commonly used for main site navigation menus, but it can also be used for secondary navigation like pagination or related links.

 

navigation-menu.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of nav Element</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        nav {
            background-color: #333;
            padding: 10px;
        }
        nav a {
            color: white;
            text-decoration: none;
            margin: 0 15px;
        }
        nav a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <header>
        <nav>
            <a href="#home">Home</a>
            <a href="#about">About</a>
            <a href="#services">Services</a>
            <a href="#contact">Contact</a>
        </nav>
    </header>
    <main>
        <section id="home">
            <h1>Welcome to the User</h1>
            <p>This is the home section.</p>
        </section>
        <section id="about">
            <h2>About Us</h2>
            <p>This is the about section.</p>
        </section>
        <section id="services">
            <h2>Our Services</h2>
            <p>This is the services section.</p>
        </section>
        <section id="contact">
            <h2>Contact Us</h2>
            <p>This is the contact section.</p>
        </section>
    </main>
    <footer>
        <p>&copy; 2024 Example Company</p>
    </footer>
</body>
</html>

 

Previous                                                    Next                                                    Home

Monday, 2 December 2024

Lazy Initialization in React's useState Hook: Boosting Performance with Functional Initial State

In this post, I am going to explain an advanced feature of React's useState hook—lazy initialization. When using useState, many developers pass a simple initial value, such as a string or number. However, when initializing state with complex computations, there's a more efficient way,  passing a function as the initial state argument. Known as "lazy initialization," this technique allows React to execute the function only once, during the first render.

By exploring this approach, we’ll understand how it helps to optimize component performance and when to consider using it.

 

Signature

const [state, setState] = useState(initialState);

 

·      state: The current state value.

·      setState: A function that allows you to update the state. When called, it queues a re-render of the component with the new state value.

·       initialState: The initial value of the state. It can be:

·      A direct value (e.g., a number, string, object).

·      A function that returns the initial value (for lazy initialization).

 

Example

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  let randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
  console.log(`randomNumber : ${randomNumber}`);
  return randomNumber;
}

const [count, setCount] = useState(() => {
  return getRandomInt(10, 100);
});

 

In this snippet, the useState hook uses a lazy initialization technique by taking a function as its argument. Lazy initialization with useState means the initial value of count is set by calling the function only once, when the component first renders.

 

Here’s how it works in this example.

·       Function Argument in useState: By passing a function (() => { return getRandomInt(10, 100); }) to useState, React only calls this function when it first needs to initialize count.

·       Benefit: Using a function for lazy initialization is beneficial when the initial state calculation (like generating a random number) is complex or involves performance-costly operations. By deferring this until the initial render, it avoids unnecessary recalculations on every re-render, as useState won’t call this function again unless the component is remounted.

 

In this case, the getRandomInt(10, 100) function generates and logs a random integer between 10 and 100, assigning that value as the initial state for count. This value is then preserved through re-renders unless updated explicitly by calling setCount.

 

 

Follow below step-by-step procedure to build the working application.

 

Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘use-state-lazy-initialization’.

 

Project structure looks like below.

 


 

Step 2: Create components folder in src folder and define Counter component.

Counter.jsx

import { useState } from "react";

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  let randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
  console.log(`randomNumber : ${randomNumber}`);
  return randomNumber;
}

export default function Counter() {
  const [count, setCount] = useState(() => {
    return getRandomInt(10, 100);
  });

  return (
    <div className="container">
      <div className="counterApp">
        <p id="counterInfo">Current Counter : {count}</p>

        <button
          id="incCounter"
          onClick={() => {
            setCount((prevValue) => prevValue + 1);
          }}
        >
          Increment By 1
        </button>
      </div>
    </div>
  );
}

Step 3: Create styles folder in src folder and define styles.css file.

 

styles.css

.container {
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
}

.counterApp {
  width: 400px;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 15px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2); /* Larger shadow for depth */
  transition: transform 0.2s ease; /* Subtle scaling on hover */
}

.counterApp:hover {
  transform: scale(1.05); /* Slight zoom effect */
}

#counterInfo {
  font-size: 2em;
  color: #333;
  margin: 15px 0;
  padding: 20px;
  border: 2px solid #0072ff;
  border-radius: 10px;
  background-color: #f7f9fc;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* Softer shadow for text area */
  text-align: center;
}

#incCounter {
  font-size: 1.5em;
  padding: 15px 25px;
  color: #ffffff;
  background-color: #0072ff;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); /* Button shadow */
  transition: background-color 0.3s ease, transform 0.2s ease;
}

Step 4: Update src/main.jsx with below content.

 

main.jsx

import { createRoot } from "react-dom/client";
import Counter from "./components/Counter";
import "./styles/styles.css";

createRoot(document.getElementById("root")).render(<Counter />);

Step 5: Follow below steps to run the Application.

  cd use-state-lazy-initialization
  npm install
  npm run dev

Open the url ‘http://localhost:5173/ ‘ in browser, you will see below screen.




Counter is initialized with some random value between 10 and 100, you can click on the button ‘Increment By 1’ to understand the behavior better.

 

You can download the Application from this link.


Previous                                                    Next                                                    Home