Wednesday, 4 December 2024

How to manage Side Effects easily using React useEffect hook?

In React, not all tasks can be achieved through rendering components alone. Some actions, like fetching data, interacting with browser APIs, or setting up subscriptions, need to happen outside the rendering process. These are called side effects and React provides the useEffect hook to manage them seamlessly in functional components. In this article, we'll explore how the useEffect hook works, why it's essential for handling side effects, and how to use it effectively in your React projects.

Syntax of useEffect

useEffect(() => {
  // Effect logic goes here (side effects like API calls, subscriptions, etc.)

  return () => {
    // Optional cleanup logic
  };
}, [dependencies]);

 

The useEffect hook in React is called under several circumstances, depending on how you configure it.

 

1. On Initial Render (Component Mounting)

When the component first renders (mounts), the useEffect hook is triggered.

useEffect(() => {
  // Code runs once when the component mounts
  console.log("Component mounted!");
}, []);  // The empty dependency array makes it run only once.

 

2. On Every Render (Component Updating)

If you omit the second argument (dependency array), the useEffect hook will run after every render (both on mount and after every update).

 

useEffect(() => {
  // Code runs after every render (initial and updates)
  console.log("Component rendered or updated!");
});

 

3. On Specific State/Props Changes

You can pass an array of specific values (state or props) as dependencies. The useEffect will run only when one of these dependencies changes.

 

const [count, setCount] = useState(0);

useEffect(() => {
  // Code runs only when 'count' changes
  console.log(`Count value is: ${count}`);
}, [count]);  // Effect depends on 'count' variable

When you pass a dependency array to useEffect, React compares the current values of the dependencies with the previous ones from the last render. This comparison allows React to decide whether the useEffect should be re-run.

 

Internally, React stores (or "caches") the previous values of the dependencies in a special way. On each render, React compares the new values of the dependencies with the cached values from the previous render:

 

1.   If all the dependencies are the same as in the previous render, the effect will not run.

2.   If any dependency has changed compared to the cached values, React will re-run the effect.

 

Example

useEffect(() => {
  console.log("Effect ran");
}, [propA, propB]);

1.   On the first render, React caches the values of propA and propB.

2.   On the next render, React compares the new propA and propB with their cached values.

o   If propA or propB has changed, React will run the effect again and update the cached values.

o   If neither has changed, React will skip running the effect.

 

4. On Component Unmounting (Cleanup)

If your useEffect returns a function, React will call that function when the component unmounts or before the effect runs again (if it's being re-executed due to a dependency change). This is useful for cleanup tasks, such as removing event listeners or canceling API calls.

useEffect(() => {
  const timer = setTimeout(() => {
    console.log("Timer finished!");
  }, 1000);

  return () => {
    // Cleanup the timer when the component unmounts or before the effect reruns
    clearTimeout(timer);
  };
}, []);  // The empty array ensures this cleanup runs only on unmount.

Let’s build an Application to understand the useEffect hook better.

 

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-effect-demo’.

 

Project structure looks like below.


 


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

 

UsersInfo.jsx

import React, { useState, useEffect } from 'react';

export default function UsersInfo() {
  const [users, setUsers] = useState([]);  // State to hold the users

  useEffect(() => {
    // This effect will run when the component is first rendered

    // Fetching data from an API
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => response.json())
      .then(data => setUsers(data))  // Update the state with the fetched data
      .catch(error => console.error('Error fetching users:', error));

  }, []);  // The empty dependency array means this runs only on the first render (once)

  return (
    <div>
      <h1>User List</h1>
      <ul>
        {users.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

Step 3: Update main.jsx file like below.

 

main.jsx

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

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <UsersInfo />
  </StrictMode>,
)

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

  cd use-effect-demo
  npm install
  npm run dev

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


 

You can download this application from this link.


Previous                                                    Next                                                    Home

Default Parameters in JavaScript

You can assign default values to function parameters. If an argument is not provided, the default value will be used.

defaultParameters.js

function greetUser(name = "Guest") {
    console.log("Hello, " + name + "!");
}

greetUser("Alice");
greetUser();

 

Output

Hello, Alice!
Hello, Guest!

function greetUser(name = "Guest") {
    console.log("Hello, " + name + "!");
}

 

The parameter name is given a default value of "Guest". This means if no argument is passed to the function when it's called, name will automatically be assigned the value "Guest".

 


Previous                                                    Next                                                    Home

Text Transformations in CSS: A beginner Guide to the text-transform Property

The text-transform property in CSS is used to control the capitalization of text in an element. It can be applied to any text-containing HTML element, such as paragraphs, headings, and spans. This property is particularly useful for standardizing the appearance of text across a website, ensuring consistency regardless of how the text is input by users or content creators.

Syntax

selector {

    text-transform: value;

}

 

Value can be one of the below.

Value

Description

Example

none

Default value. The text is displayed as it is written in the HTML without any transformation.

p.normal {

    text-transform: none;

}

capitalize

Transforms the first character of each word to uppercase. All other characters remain unchanged.

p.capitalize {

    text-transform: capitalize;

}

uppercase

Transforms all characters in the text to uppercase.

p.uppercase {

    text-transform: uppercase;

}

lowercase

Transforms all characters in the text to lowercase.

p.lowercase {

    text-transform: lowercase;

}

full-width

Converts the text to full-width form, which is used in East Asian typography.

p.full-width {

    text-transform: full-width;

}

 

 

textTransform.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Text Transform Example</title>
    <style>
        p {
            font-size: 16px;
            margin-bottom: 10px;
        }

        p.uppercase {
            text-transform: uppercase;
        }

        p.lowercase {
            text-transform: lowercase;
        }

        p.capitalize {
            text-transform: capitalize;
        }

        p.full-width{
            text-transform: full-width;
        }
    </style>
</head>
<body>
    <p class="uppercase">This text will be in uppercase.</p>
    <p class="lowercase">THIS TEXT WILL BE IN LOWERCASE.</p>
    <p class="capitalize">this text will be capitalized.</p>
    <p class="full-width">this text will be in full width form</p>
</body>
</html>


 

 

  

Previous                                                    Next                                                    Home

Enhance Webpage Navigation: Using Anchor Tags for Internal Links

Using the combination of the href attribute in the anchor tag and the id attribute in the target element, we can refer to internal sections in an HTML document using the anchor (<a>) tag.

 

Step 1: Assign an id to the Target Element. The element you want to navigate to should have a unique id attribute. This id acts as a marker or identifier for the section.

 

Step 2: Create an Anchor (<a>) Tag with the href Attribute. In the anchor tag, use the href attribute to refer to the id of the target element. The href value should start with a # followed by the id.

 

Example

<a href="#section1">Go to Section 1</a>

 

internal-links.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Internal Linking Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
        }
        nav {
            background-color: #4CAF50;
            color: white;
            padding: 15px;
            text-align: center;
            position: fixed;
            width: 100%;
            top: 0;
            left: 0;
        }
        nav a {
            color: white;
            margin: 0 15px;
            text-decoration: none;
            font-size: 18px;
        }
        .section {
            padding: 50px;
            margin-top: 50px; /* Avoid overlap with the fixed nav bar */
            height: 500px;
        }
        #section1 { background-color: #f4f4f4; }
        #section2 { background-color: #e2e2e2; }
        #section3 { background-color: #cfcfcf; }
        #section4 { background-color: #b2b2b2; }
        #section5 { background-color: #999; }
    </style>
</head>
<body>

    <!-- Navigation Bar -->
    <nav>
        <a href="#section1">Go to Section 1</a>
        <a href="#section2">Go to Section 2</a>
        <a href="#section3">Go to Section 3</a>
        <a href="#section4">Go to Section 4</a>
        <a href="#section5">Go to Section 5</a>
    </nav>

    <!-- Sections -->
    <div id="section1" class="section">
        <h2>Section 1</h2>
        <p>This is the content of section 1.</p>
    </div>

    <div id="section2" class="section">
        <h2>Section 2</h2>
        <p>This is the content of section 2.</p>
    </div>

    <div id="section3" class="section">
        <h2>Section 3</h2>
        <p>This is the content of section 3.</p>
    </div>

    <div id="section4" class="section">
        <h2>Section 4</h2>
        <p>This is the content of section 4.</p>
    </div>

    <div id="section5" class="section">
        <h2>Section 5</h2>
        <p>This is the content of section 5.</p>
    </div>

</body>
</html>

 

Above snippet generate below screen.

 


 

Click on the links at navigation links, it takes you through the respective sections.


Previous                                                    Next                                                    Home

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