Sunday, 8 December 2024

React useEffect Cleanup: Why and When It's Needed

In React, a component's lifecycle refers to the different stages it goes through from the moment it is created (mounted) to the moment it is destroyed (unmounted).

Let’s understand each stage in detail.

 

1. Mounting

This is when a component is created and added (rendered) to the DOM. During this stage, the component's constructor, render method, and any initial side effects (like useEffect) will run.

 

Common states in mounting

1.   The component's initial state is set (e.g., useState).

2.   The useEffect hook (with an empty dependency array []) runs after the component renders for the first time.

 

2. Updating

Once the component is mounted, it can update due to changes in its props or state. React re-renders the component when necessary and trigger the updates.

 

Common states in updating

1.   When a component's props or state changes, the render method is called again.

2.   If the component has a useEffect with dependencies, it will re-run the effect when the specified dependencies change.

3.   This is the phase where React compares the Virtual DOM with the real DOM to update the UI efficiently.

 

3. Unmounting

Unmounting is the process where a component is removed from the DOM. This can happen for several reasons, such as:

 

1.   Navigation to a different route.

2.   The parent component no longer renders the child component.

3.   Conditional rendering based on state.

 

When a component is unmounted

1.   The component is completely removed from the DOM.

2.   This is where the cleanup function from useEffect comes into play. Before the component is removed, any ongoing effects (like event listeners, subscriptions, or timers) should be cleaned up to prevent memory leaks or errors. This cleanup function will be executed when the component unmounts or before the effect re-runs.

 

Example

<!-- HTML generated using hilite.me --><div style="background: #ffffff; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;"><pre style="margin: 0; line-height: 125%"><span style="color: #008800; font-weight: bold">import</span> React, { useState, useEffect } from <span style="background-color: #fff0f0">&quot;react&quot;</span>;

<span style="color: #008800; font-weight: bold">const</span> WindowSizeTracker <span style="color: #333333">=</span> () <span style="color: #333333">=&gt;</span> {
  <span style="color: #008800; font-weight: bold">const</span> [windowWidth, setWindowWidth] <span style="color: #333333">=</span> useState(<span style="color: #007020">window</span>.innerWidth);

  <span style="color: #888888">// Effect to handle window resize event</span>
  useEffect(() <span style="color: #333333">=&gt;</span> {
    console.log(<span style="background-color: #fff0f0">&quot;Component mounted&quot;</span>);
    <span style="color: #008800; font-weight: bold">const</span> handleResize <span style="color: #333333">=</span> () <span style="color: #333333">=&gt;</span> {
      setWindowWidth(<span style="color: #007020">window</span>.innerWidth);
    };

    <span style="color: #888888">// Add event listener on component mount</span>
    <span style="color: #007020">window</span>.addEventListener(<span style="background-color: #fff0f0">&quot;resize&quot;</span>, handleResize);

    <span style="color: #888888">// Cleanup function to remove event listener on unmount</span>
    <span style="color: #008800; font-weight: bold">return</span> () <span style="color: #333333">=&gt;</span> {
      console.log(<span style="background-color: #fff0f0">&quot;Component unmounted, un-registering resize event&quot;</span>);
      <span style="color: #007020">window</span>.removeEventListener(<span style="background-color: #fff0f0">&quot;resize&quot;</span>, handleResize);
    };
  }, []); <span style="color: #888888">// Empty array ensures this effect runs only once</span>

  <span style="color: #008800; font-weight: bold">return</span> (
    <span style="color: #333333">&lt;</span>div<span style="color: #333333">&gt;</span>
      <span style="color: #333333">&lt;</span>h1<span style="color: #333333">&gt;</span>Window Width<span style="color: #333333">:</span> {windowWidth}<span style="color: #333333">&lt;</span><span style="color: #FF0000; background-color: #FFAAAA">/h1&gt;</span>
    <span style="color: #333333">&lt;</span><span style="color: #FF0000; background-color: #FFAAAA">/div&gt;</span>
  );
};
</pre></div>

 

In the provided snippet, the cleanup of resources is handled through the useEffect hook, specifically using the return function.

 

When the component mounts, an event listener for the window's resize event is added using window.addEventListener("resize", handleResize);. This listener updates the component's state (windowWidth) whenever the window is resized.

 

Cleanup Function

The useEffect hook returns a cleanup function (return () => { ... };), which is called when the component unmounts or before the effect runs again (if dependencies change). In this case, the cleanup function logs a message indicating that the component is being unmounted and un-registers the resize event listener with window.removeEventListener("resize", handleResize);.

 

Why Cleanup is Important?

1.   Prevents Memory Leaks: By removing the event listener when the component is unmounted, you prevent potential memory leaks that could occur if the listener were to remain active.

2.   Avoids Performance Issues: Without cleanup, if the component is toggled on and off repeatedly, multiple event listeners could stack up, leading to performance degradation.

 

Let us try to understand this with a detailed example.

 

Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘cleanup-using-use-effect-hook’

 

Project structure looks like below.



Step 2: Create components folder in src/ folder and define window size tracker component.

 

WindowSizeTracker.jsx

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

const WindowSizeTracker = () => {
  const [windowWidth, setWindowWidth] = useState(window.innerWidth);

  // Effect to handle window resize event
  useEffect(() => {
    console.log("Component mounted");
    const handleResize = () => {
      setWindowWidth(window.innerWidth);
    };

    // Add event listener on component mount
    window.addEventListener("resize", handleResize);

    // Cleanup function to remove event listener on unmount
    return () => {
      console.log("Component unmounted, un-registering resize event");
      window.removeEventListener("resize", handleResize);
    };
  }, []); // Empty array ensures this effect runs only once

  return (
    <div>
      <h1>Window Width: {windowWidth}</h1>
    </div>
  );
};

export default WindowSizeTracker;

 

Step 3: Update App.jsx file like below.

 

App.jsx
import React, { useState } from "react";
import WindowSizeTracker from "./components/WindowSizeTracker";

const App = () => {
  const [showComponent, setShowComponent] = useState(true);

  return (
    <div>
      <button onClick={() => setShowComponent(!showComponent)}>
        {showComponent ? "Hide Component" : "Show Component"}
      </button>
      {showComponent && <WindowSizeTracker />}
    </div>
  );
};

export default App;

Step 4: Update main.jsx file like below.

 

main.jsx

import { createRoot } from "react-dom/client";
import App from "./App.jsx";

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

Step 5: Follow below steps to build and run the Application.

  cd cleanup-using-use-effect-hook
  npm install
  npm run dev

You can download this application from this link.


Previous                                                    Next                                                    Home

Saturday, 7 December 2024

Global variables in JavaScript

Global variables in JavaScript are variables that are accessible throughout the entire script or application, regardless of where they are declared. They can be accessed and modified from any part of the code. Understanding global variables is crucial, especially in larger applications, where their improper use can lead to issues like unexpected behavior, conflicts, and difficulty in debugging.

How Global Variables are Created?

Declaring Variables Outside Any Function

When a variable is declared outside of any function using the var, let, or const keywords, it becomes a global variable.

var globalVar = "I am global";
let globalLet = "I am also global";
const globalConst = "I am global and constant";

function checkGlobal() {
    console.log(globalVar);
    console.log(globalLet);
    console.log(globalConst);
}

Variables Declared Without var, let, or const

If a variable is declared without the var, let, or const keywords inside a function, it automatically becomes a global variable.

function makeGlobal() {
    globalVarWithoutKeyword = "I am global without var, let or const";
}

makeGlobal();
console.log(globalVarWithoutKeyword);

Find the below working application.

 

globalVariablesCreation.js

var globalVar = "I am global";
let globalLet = "I am also global";
const globalConst = "I am global and constant";

function checkGlobal() {
    console.log(globalVar);
    console.log(globalLet);
    console.log(globalConst);
}

checkGlobal();

function makeGlobal() {
    globalVarWithoutKeyword = "I am global without var, let or const";
}

makeGlobal();
console.log(globalVarWithoutKeyword);

Output

I am global
I am also global
I am global and constant
I am global without var, let or const



 

However, if you declare a variable using let or const, it does not become a property of the window object.



Points to consider while using global variables

1.   Global variables can be unintentionally overwritten by other parts of the code or by external libraries.

 

2.   Using global variables can lead to tight coupling between different parts of the application, making the code harder to maintain.

 

3.   Global variables remain in memory for as long as the application is running, which can lead to higher memory consumption.

 

4.   Tracking the usage and modification of global variables across large codebases can be challenging, leading to bugs that are difficult to trace.

 

5.   Avoid using global variables as much as possible. Prefer using function-scoped or block-scoped variables with let and const.

 


Previous                                                    Next                                                    Home

A Beginner Guide to Using the font-size Property in CSS

The font-size property in CSS is used to control the size of the text on a webpage. This property can take several types of values, each suited to different scenarios, especially when aiming to make a page more responsive. Here's an overview of the different values you can use with the font-size property:

1. Absolute Units

·      px (pixels): Specifies an exact number of pixels. For example, font-size: 16px; sets the font size to 16 pixels. While this is precise, it's not very responsive because it doesn't scale based on the user's screen size or settings.

·      pt (points): Commonly used in print media. One point is 1/72 of an inch. Like pixels, it’s not very responsive.

·      cm, mm, in, pc, em: These are other absolute units, but they are rarely used for font sizing on the web.

 

2. Relative Units

·      em: Relative to the font size of the parent element. For example, font-size: 2em; means twice the size of the parent element's font size. This is useful for scaling text proportionally across different elements.

·      rem: Relative to the root element (<html>)'s font size. For example, font-size: 1.5rem; means 1.5 times the root element's font size. This is often preferred over em for consistency across the site.

·      % (percentage): Relative to the parent element's font size. For example, font-size: 150%; means 150% of the parent's font size. This can be useful for making text scale according to its container.

·      vw (viewport width): A percentage of the width of the viewport (browser window). For example, font-size: 2vw; sets the font size to 2% of the viewport width, making it responsive to screen size changes.

·      vh (viewport height): A percentage of the height of the viewport. For example, font-size: 2vh; adjusts the font size based on the height of the viewport.

·      vmin and vmax: Relative to the smaller (vmin) or larger (vmax) of the viewport’s width or height. These can be useful for ensuring text scales proportionately regardless of the viewport’s dimensions.

 

3. Keywords

·      xx-small, x-small, small, medium, large, x-large, xx-large: These are predefined keyword values that set the font size relative to the user agent's (browser's) default font size.

·      smaller, larger: These are relative to the parent element's font size. smaller will reduce the font size slightly, while larger will increase it.

 

fontSize.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Font Size Units in CSS</title>
    <style>
        /* Absolute Units */
        .absolute-px { font-size: 16px; }
        .absolute-pt { font-size: 12pt; }
        .absolute-cm { font-size: 1cm; }
        .absolute-mm { font-size: 10mm; }
        .absolute-in { font-size: 1in; }
        .absolute-pc { font-size: 12pc; }

        /* Relative Units */
        .relative-em { font-size: 1.5em; }
        .relative-rem { font-size: 2rem; }
        .relative-percent { font-size: 150%; }
        .relative-vw { font-size: 5vw; }
        .relative-vh { font-size: 5vh; }
        .relative-vmin { font-size: 5vmin; }
        .relative-vmax { font-size: 5vmax; }

        /* Font Size Keywords */
        .keyword-xx-small { font-size: xx-small; }
        .keyword-x-small { font-size: x-small; }
        .keyword-small { font-size: small; }
        .keyword-medium { font-size: medium; }
        .keyword-large { font-size: large; }
        .keyword-x-large { font-size: x-large; }
        .keyword-xx-large { font-size: xx-large; }
        .keyword-smaller { font-size: smaller; }
        .keyword-larger { font-size: larger; }

        /* Fluid Typography */
        .fluid-typography { font-size: calc(16px + 1vw); }

        /* Clamp Example */
        .clamp-font-size { font-size: clamp(1rem, 2vw, 2rem); }
    </style>
</head>
<body>
    <h1>CSS Font Size Units</h1>

    <!-- Absolute Units -->
    <h2>Absolute Units</h2>
    <p class="absolute-px">This text is 16px in size (pixels).</p>
    <p class="absolute-pt">This text is 12pt in size (points).</p>
    <p class="absolute-cm">This text is 1cm in size (centimeters).</p>
    <p class="absolute-mm">This text is 10mm in size (millimeters).</p>
    <p class="absolute-in">This text is 1in in size (inches).</p>
    <p class="absolute-pc">This text is 12pc in size (picas).</p>

    <!-- Relative Units -->
    <h2>Relative Units</h2>
    <p class="relative-em">This text is 1.5em in size (relative to parent element).</p>
    <p class="relative-rem">This text is 2rem in size (relative to root element).</p>
    <p class="relative-percent">This text is 150% of the parent element's font size.</p>
    <p class="relative-vw">This text is 5vw in size (5% of the viewport width).</p>
    <p class="relative-vh">This text is 5vh in size (5% of the viewport height).</p>
    <p class="relative-vmin">This text is 5vmin in size (5% of the smaller viewport dimension).</p>
    <p class="relative-vmax">This text is 5vmax in size (5% of the larger viewport dimension).</p>

    <!-- Font Size Keywords -->
    <h2>Font Size Keywords</h2>
    <p class="keyword-xx-small">This text is xx-small.</p>
    <p class="keyword-x-small">This text is x-small.</p>
    <p class="keyword-small">This text is small.</p>
    <p class="keyword-medium">This text is medium.</p>
    <p class="keyword-large">This text is large.</p>
    <p class="keyword-x-large">This text is x-large.</p>
    <p class="keyword-xx-large">This text is xx-large.</p>
    <p class="keyword-smaller">This text is smaller than its parent.</p>
    <p class="keyword-larger">This text is larger than its parent.</p>

    <!-- Fluid Typography -->
    <h2>Fluid Typography</h2>
    <p class="fluid-typography">This text uses fluid typography with <code>calc(16px + 1vw)</code>.</p>

    <!-- Clamp Example -->
    <h2>Clamp Font Size</h2>
    <p class="clamp-font-size">This text uses <code>clamp(1rem, 2vw, 2rem)</code> for responsive font sizing.</p>
</body>
</html>


 

 

  

Previous                                                    Next                                                    Home

href="/" : Link or point to the homepage or main entry point of the website

The href="/" link points to the root directory of the website. In other words, it links to the homepage or the main entry point of the website.

 

When a user clicks a link with href="/", the browser will navigate to the root URL of the current domain. For example, if the website URL is https://www.example.com/, clicking a link with href="/" will take the user to https://www.example.com.

 

Using href="/" makes the website more portable. If the site’s domain changes, all internal links pointing to the root will still function correctly without needing to update them.

 

Previous                                                    Next                                                    Home