Saturday, 4 January 2025

Optimizing Performance in React with the useCallback Hook

The useCallback hook in React is used to memorize functions, allowing you to "cache" a function instance and avoid unnecessary re-creations on re-renders.

Signature

const memoizedCallback = useCallback(callback, dependencies);

callback: This is the function you want to memoize. useCallback will return a memoized version of this function, meaning it won’t be recreated on each render unless its dependencies change.

 

dependencies: This is an array of values that the function depends on. The function will only be recreated if one or more of these dependencies change. If no dependencies are provided (i.e., an empty array []), the function will remain the same across all renders after the initial one.

 

Example

const memoziedFunction = useCallback(() => {
  localVar1++;
  console.log(`Memoized function : localVar : ${localVar1}`);
}, []);

Let’s build an application to understand custom 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-callback-demo’

 

Project structure looks like below.

 


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

 

HelloWorld.jsx

import { useCallback, useEffect, useState } from "react";

export default function HelloWorld() {
  const [counter, setCounter] = useState(0);
  let localVar1 = 0;
  let localVar2 = 0;

  const memoziedFunction = useCallback(() => {
    localVar1++;
    console.log(`Memoized function : localVar : ${localVar1}`);
  }, []);

  const regularFunction = () => {
    localVar2++;
    console.log(`Regular function : localVar : ${localVar2}`);
  };

  useEffect(() => {
    memoziedFunction();
    regularFunction();
  }, [counter]);

  return (
    <div>
      <button
        onClick={(event) => {
          setCounter((counter) => counter + 1);
        }}
      >
        Increment Counter
      </button>
    </div>
  );
}

Step 3: Update main.jsx with below content.

 

main.jsx

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

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

Step 4: Run the Application by executing following commands.

cd use-callback-demo
npm install
npm run dev

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



Go inspect tool -> Console tab, you can observe following messages.

Memoized function : localVar : 1 
Regular function : localVar : 1
Memoized function : localVar : 2 
Regular function : localVar : 1
Memoized function : localVar : 3 
Regular function : localVar : 1
Memoized function : localVar : 4 
Regular function : localVar : 1

Memoized Function Behavior (memoziedFunction)

Since useCallback is used with an empty dependency array ([]), memoziedFunction is created only once and retains its reference across all renders. localVar1 behaves like a persistent closure within memoziedFunction. Each time memoziedFunction is called, it increments localVar1 from its previous value, rather than resetting to 0 on each render.

 

This is why localVar1 keeps increasing with each useEffect call. It retains its incremented state within the useCallback closure, even though it’s technically a local variable.

 

Regular Function Behavior (regularFunction)

regularFunction is recreated on every render, so localVar2 resets to 0 each time regularFunction is redefined.

 

Each time regularFunction is called, localVar2 increments from 0 to 1, and then logs this value, giving the impression of a reset. This happens because the function doesn’t have a stable reference, so it doesn’t retain any previous state.

  

Previous                                                    Next                                                    Home

Conditional Statements in JavaScript

Conditional statements in JavaScript allow you to perform different actions based on different conditions. They are fundamental in controlling the flow of a program, making decisions, and responding to various inputs. Here's a detailed breakdown:

1. if Statement

The if statement executes a block of code if a specified condition is true.

 

Syntax

if (condition) {
  // code to be executed if the condition is true
}

 

ifCondition.js

let x = 10;

if (x > 5) {
  console.log(`x is greater than than 5, x : ${x}`)
}

if (x < 5) {
  console.log(`x is less than than 5, x : ${x}`)
}

Output

x is greater than than 5, x : 10

In this example, the message " x is greater than than 5, x : 10" will be printed because the condition x > 5 is true.

 

2. else Statement

The else statement executes a block of code if the condition in the if statement is false.

 

Syntax

if (condition) {
  // code to be executed if the condition is true
} else {
  // code to be executed if the condition is false
}

ifElse.js

let x = 3;

console.log(`x = ${x}`);

if (x > 5) {
  console.log("x is greater than 5");
} else {
  console.log("x is not greater than 5");
}

Output

x = 3
x is not greater than 5

Here, the message "x is not greater than 5" will be printed because x > 5 is false.

 

3. else if Statement

The else if statement specifies a new condition to test if the first condition is false.

 

Syntax

if (condition1) {
  // code to be executed if condition1 is true
} else if (condition2) {
  // code to be executed if condition1 is false and condition2 is true
} else if (condition3) {
  // code to be executed if condition2 is false and condition3 is true
}else {
  // code to be executed if condition1 and condition2 are both false
}

ifElseIf.js

let x = 10;

console.log(`x : ${x}`);

if (x > 15) {
  console.log("x is greater than 15");
} else if (x > 5) {
  console.log("x is greater than 5 but less than or equal to 15");
} else {
  console.log("x is 5 or less");
}

Output

x : 10
x is greater than 5 but less than or equal to 15

In this case, "x is greater than 5 but less than or equal to 15" is printed because the first condition is false, but the second condition is true.

 

4. switch Statement

The switch statement is used to perform different actions based on different possible values of an expression. It’s an alternative to multiple else if statements.

 

Syntax

switch(expression) {
  case value1:
    // code to be executed if expression === value1
    break;
  case value2:
    // code to be executed if expression === value2
    break;
  // additional cases...
  default:
    // code to be executed if none of the above cases match
}

switchDemo.js

let color = "red";

console.log(`Color: ${color}`);

switch(color) {
  case "blue":
    console.log("Color is blue");
    break;
  case "red":
    console.log("Color is red");
    break;
  case "green":
    console.log("Color is green");
    break;
  default:
    console.log("Color is not blue, red, or green");
}

Output

Color: red
Color is red

This will print "Color is red" because the color variable matches the "red" case.

 

5. Ternary Operator (?:)

The ternary operator is a shorthand for the if-else statement.

 

Syntax

condition ? expressionIfTrue : expressionIfFalse

ternary.js

let age = 18;

console.log(`age: ${age}`);

let canVote = age >= 18 ? "Yes, you can vote" : "No, you cannot vote";

console.log(canVote);

Output

age: 18
Yes, you can vote

This will print "Yes, you can vote" because age >= 18 is true.

 

6. Nested Conditional Statements

You can nest conditional statements within each other to handle more complex logic.

 

nestedConditionalStatement.js

let score = 85;

console.log(`Score: ${score}`);

if (score >= 90) {
  console.log("Grade: A");
} else {
  if (score >= 80) {
    console.log("Grade: B");
  } else {
    if (score >= 70) {
      console.log("Grade: C");
    } else {
      console.log("Grade: D or below");
    }
  }
}

Output

Score: 85
Grade: B

8. switch with Multiple Cases

You can group multiple cases together if they should execute the same code.

 

switchMultiCase.js

let day = 3;

switch(day) {
  case 1:
  case 2:
  case 3:
  case 4:
  case 5:
    console.log("It's a weekday");
    break;
  default:
    console.log("It's the weekend!");
}

Output

It's a weekday

 

Previous                                                    Next                                                    Home

Introduction To CSS Box Model

The CSS box model is a fundamental concept that underlies the layout and design of web pages. It describes how the elements on a web page are structured and spaced. Understanding the box model is essential for controlling the appearance and positioning of elements.

1. Components of the CSS Box Model

Every HTML element is considered a box, and the CSS box model consists of the following components.

 


1.1 Content Box

This is the innermost part of the box. It holds the actual content such as text, images, or other elements. Properties like width and height directly affect the size of the content box. The content-box is the default value for the box-sizing property.

 

1.2 Padding

Definition: Padding is the space between the content and the border.

Properties like padding, padding-top, padding-right, padding-bottom, padding-left are used to control the padding area.

 

1.3 Border

The border surrounds the padding (if any) and content. It can have a specific thickness, style, and color. Properties like border, border-width, border-style, border-color, border-top, border-right, border-bottom, border-left are used to control the broder.

 

1.4 Margin

Margin is the space outside the border, separating the element from its neighbors. It is used for creating space between elements.

Properties like margin, margin-top, margin-right, margin-bottom, margin-left are used to control the margin.

 

Understanding the box model is essential for creating layouts, especially when using CSS properties like float, position, flex, and grid. These properties affect how boxes behave and interact with each other.

 

box-model-demo.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Box Model without Box-Sizing</title>
    <style>
        .box {
            width: 300px;    /* Width applies only to the content */
            padding: 20px;   /* Padding adds space inside the element */
            border: 10px solid #007BFF;  /* Border around the element */
            background-color: #f0f8ff;
            margin-bottom: 20px;  /* Margin outside the element */
        }
    </style>
</head>
<body>

    <h1>Box Model Example</h1>

    <!-- Box demonstrating default behavior (content-box) -->
    <div class="box">
        This box is using the default box-sizing behavior.
        The width of the content area is 300px, and the total width will be larger due to padding and border.
    </div>

</body>
</html>





Previous                                                    Next                                                    Home

How to Use Colspan and Rowspan in HTML Tables?

The colspan and rowspan attributes in HTML tables allow you to merge cells either horizontally (across columns) or vertically (across rows), which is useful for organizing complex data.

colspan Attribute

The colspan attribute in a <th> or <td> element specifies the number of columns a cell should span. It merges the current cell with the adjacent cells to the right.

 

rowspan Attribute

The rowspan attribute specifies the number of rows a cell should span. It merges the current cell with the cells directly below it.

 

row-and-column-span.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML Table with Colspan and Rowspan</title>
</head>
<body>
    <h1>HTML Table Example with Colspan and Rowspan</h1>

    <table border="1">
        <caption>Employee Shift Schedule</caption>
        <thead>
            <tr>
                <th>Employee Name</th>
                <th>Shift</th>
                <th>Days</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td rowspan="2">Rama Krishna</td>
                <td>Morning</td>
                <td>Monday</td>
            </tr>
            <tr>
                <td>Morning</td>
                <td>Tuesday</td>
            </tr>
            <tr>
                <td>Gopi Battu</td>
                <td colspan="2">Afternoon Shift (Wednesday and Thursday)</td>
            </tr>
            <tr>
                <td>Joel Chelli</td>
                <td>Night</td>
                <td>Friday</td>
            </tr>
        </tbody>
    </table>
    
</body>
</html>

 


 

  

Previous                                                    Next                                                    Home