Popular Searches
Popular Course Categories
Popular Courses

Managing Event Listeners

Managing Event Listeners

React Side Effects and Lifecycle

Managing Event Listeners in React

Managing Event Listeners is an important concept in React that involves adding, handling, and removing browser event listeners to respond to user actions and browser events. React provides built-in event handling through JSX, while native JavaScript methods such as addEventListener() and removeEventListener() are useful when working with global browser events or external systems.

In these notes, you will learn about event listeners, React event handling, the useEffect() Hook, cleanup functions, keyboard events, mouse events, window resizing, scrolling, common mistakes, practical examples, and interview questions.

React JS Training: Explore JustAcademy React JS Training
Course Demo: Register for React JS Course Demo


1. What Are Event Listeners?

An event listener is a function registered to respond when a particular event occurs. Events can be triggered by user actions, browser activity, or interactions with HTML elements.

For example, an event listener can respond when a user clicks a button, presses a keyboard key, scrolls a page, resizes a browser window, or moves the mouse.

Common browser events

Event Description Example use
click Triggered when an element is clicked. Opening a menu.
dblclick Triggered when an element is double-clicked. Opening an item for editing.
keydown Triggered when a key is pressed down. Keyboard shortcuts.
keyup Triggered when a key is released. Detecting completed key presses.
mousemove Triggered when the pointer moves. Tracking pointer position.
scroll Triggered when a scrollable area moves. Showing a back-to-top button.
resize Triggered when the browser window is resized. Updating a responsive layout indicator.
focus Triggered when an element receives focus. Displaying form guidance.
blur Triggered when an element loses focus. Validating a form field.
submit Triggered when a form is submitted. Processing form data.

2. How Does Event Handling Work in React?

React supports event handling through JSX props such as onClick, onChange, onSubmit, and onKeyDown. You usually do not need to manually register a native event listener for ordinary interactions with React elements.

Example: Handling a Button Click

function Welcome() {
  function handleClick() {
    alert("Welcome to React!");
  }

  return (
    <button onClick={handleClick}>
      Click Me
    </button>
  );
}

export default Welcome;

Explanation:

  • handleClick is the event handler function.
  • onClick registers the handler through React.
  • React invokes the handler when the button is clicked.
  • The function is passed as a reference, not called during rendering.

Important: Write onClick={handleClick}, not onClick={handleClick()}, when you want React to call the handler in response to a click.

3. Native Event Listeners in JavaScript

JavaScript provides the addEventListener() method to register an event listener on an object such as window, document, or a DOM element.

Syntax

target.addEventListener(eventType, handler, options);
  • target: The object that receives the event.
  • eventType: The event name, such as "click" or "resize".
  • handler: The function that runs when the event occurs.
  • options: Optional configuration, such as capture mode or passive handling.

Example

function handleClick() {
  console.log("Button clicked");
}

document.addEventListener("click", handleClick);

This example registers a listener on the document, so clicks that reach the document can trigger the handler. In a React component, a native listener should be removed when it is no longer needed.

4. Why Manage Event Listeners in React?

Managing event listeners ensures that browser events are handled at the appropriate time and that listeners do not remain active after a component no longer needs them.

  • Global events: Listen for browser-level keyboard, resize, or scroll events.
  • External integrations: Connect React components to browser APIs or third-party libraries.
  • Resource management: Remove listeners when they are no longer required.
  • Prevent duplicate handlers: Avoid registering multiple copies of the same logical listener.
  • Reliable behaviour: Keep event handling synchronized with the component's current props and state.

5. Using useEffect() to Manage Event Listeners

The useEffect() Hook lets a functional component synchronize with external systems, including browser event subscriptions. It can register a listener and return a cleanup function to remove it.

Basic syntax

import { useEffect } from "react";

useEffect(() => {
  function handleEvent() {
    // Respond to the event
  }

  window.addEventListener("resize", handleEvent);

  return () => {
    window.removeEventListener("resize", handleEvent);
  };
}, []);

How it works:

  1. React commits the component to the page.
  2. The Effect registers the event listener.
  3. The browser calls the handler when the event occurs.
  4. React runs the cleanup function when the Effect is replaced or the component is removed.
  5. The cleanup function unregisters the listener.

The empty dependency array means the Effect has no reactive dependencies. In development Strict Mode, React may run an additional setup-and-cleanup cycle to check whether the cleanup correctly reverses the setup.

6. Understanding removeEventListener()

The removeEventListener() method unregisters a previously registered event listener.

target.removeEventListener(eventType, handler, options);

For removal to work, use the same event type, the same function reference, and a matching capture setting that was used during registration.

Incorrect example

useEffect(() => {
  window.addEventListener("resize", () => {
    console.log("Window resized");
  });

  return () => {
    window.removeEventListener("resize", () => {
      console.log("Window resized");
    });
  };
}, []);

Why is this incorrect? Each arrow function creates a different function object. The cleanup therefore does not remove the original listener.

Correct example

useEffect(() => {
  function handleResize() {
    console.log("Window resized");
  }

  window.addEventListener("resize", handleResize);

  return () => {
    window.removeEventListener("resize", handleResize);
  };
}, []);

Both methods use the same handleResize function reference, allowing the browser to remove the registered listener.

7. Example: Tracking Window Resize

Sometimes an application needs to know the current browser window width. The following component listens for the resize event and updates React state.

import { useEffect, useState } from "react";

function WindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    function handleResize() {
      setWidth(window.innerWidth);
    }

    window.addEventListener("resize", handleResize);

    return () => {
      window.removeEventListener("resize", handleResize);
    };
  }, []);

  return (
    <div>
      <h2>Window Width</h2>
      <p>Current width: {width}px</p>
    </div>
  );
}

export default WindowWidth;

Explanation:

  • useState() stores the current window width.
  • window.innerWidth reads the browser viewport width.
  • handleResize() updates the state when the window changes size.
  • addEventListener() registers the listener.
  • removeEventListener() removes it during cleanup.

Note: This example assumes the component runs in the browser. In server-rendered applications, avoid accessing window during rendering; initialize browser-dependent state safely on the client.

8. Example: Listening for Keyboard Events

Keyboard listeners are useful for shortcuts, closing dialogs with Escape, and responding to specific keys while a component is active.

import { useEffect, useState } from "react";

function KeyboardListener() {
  const [message, setMessage] = useState("Press the Escape key");

  useEffect(() => {
    function handleKeyDown(event) {
      if (event.key === "Escape") {
        setMessage("Escape key pressed");
      }
    }

    window.addEventListener("keydown", handleKeyDown);

    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, []);

  return <p>{message}</p>;
}

export default KeyboardListener;

How it works: The listener detects keyboard events on the window. When the pressed key is Escape, the handler updates the message shown by the component.

Best practice: Use native keyboard listeners only when necessary. For ordinary keyboard interactions with an input or button, React props such as onKeyDown are usually simpler and more accessible.

9. Example: Listening for Scroll Events

A scroll listener can be used to display a button after a user scrolls down a long page.

import { useEffect, useState } from "react";

function BackToTop() {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    function handleScroll() {
      setVisible(window.scrollY > 250);
    }

    window.addEventListener("scroll", handleScroll, {
      passive: true
    });

    handleScroll();

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  function scrollToTop() {
    window.scrollTo({
      top: 0,
      behavior: "smooth"
    });
  }

  return (
    <div>
      {visible && (
        <button onClick={scrollToTop}>
          Back to Top
        </button>
      )}
    </div>
  );
}

export default BackToTop;

The component checks the vertical scroll position and displays a button when the user has scrolled more than 250 pixels. The button uses React's built-in click handling to return to the top of the page.

10. React Event Props vs. Native Event Listeners

Feature React event props Native event listeners
Registration Use JSX props such as onClick. Use addEventListener().
Common target React-rendered elements. window, document, DOM nodes, or other event targets.
Cleanup React manages event subscriptions for rendered elements. Usually remove manually when no longer needed.
Typical use Button clicks, form submission, input changes. Global keyboard events, window resize, external event sources.
Handler syntax onClick={handleClick} addEventListener("click", handleClick)

Use React event props by default for events on React-rendered elements. Choose native listeners when you need to subscribe directly to a browser or external event target.

11. Preventing Memory Leaks and Duplicate Listeners

If a component repeatedly registers event listeners without removing obsolete ones, multiple handlers may respond to a single event. This can lead to duplicated actions, unnecessary work, and unexpected state updates.

Example of a potential problem

function Example() {
  window.addEventListener("resize", () => {
    console.log("Resized");
  });

  return <p>Example component</p>;
}

This code registers a new listener during every render and does not provide cleanup. It should not be used in a React component.

Improved approach

function Example() {
  useEffect(() => {
    function handleResize() {
      console.log("Resized");
    }

    window.addEventListener("resize", handleResize);

    return () => {
      window.removeEventListener("resize", handleResize);
    };
  }, []);

  return <p>Example component</p>;
}

This version registers the listener inside an Effect and removes it during cleanup. Make sure useEffect is imported from React.

12. Managing Event Listeners When Dependencies Change

Sometimes an event listener needs to use a value that changes, such as a selected theme or current user ID. Include reactive values used by the Effect in its dependency array.

import { useEffect } from "react";

function ThemeLogger({ theme }) {
  useEffect(() => {
    function handleKeyDown(event) {
      if (event.key === "t") {
        console.log("Current theme:", theme);
      }
    }

    window.addEventListener("keydown", handleKeyDown);

    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [theme]);

  return <p>Current theme: {theme}</p>;
}

export default ThemeLogger;

When theme changes, React cleans up the previous listener and registers a new one that uses the latest theme. This keeps the handler synchronized with the component's current props.

13. Event Listener Options

The addEventListener() method supports options that influence how events are handled.

Option Purpose
capture Registers the listener for the capture phase when enabled.
once Automatically removes the listener after it is invoked once.
passive Signals that the handler will not call preventDefault(), which can help browser scrolling performance.
signal Allows an AbortSignal to control the listener's lifetime.

Example using once

useEffect(() => {
  function handleFirstClick() {
    console.log("First click detected");
  }

  window.addEventListener("click", handleFirstClick, {
    once: true
  });

  return () => {
    window.removeEventListener("click", handleFirstClick);
  };
}, []);

The browser automatically removes the listener after the first click. The cleanup remains useful because the component could be removed before the event occurs.

14. Using AbortController to Manage Listener Cleanup

An AbortController can manage the lifetime of event listeners by passing its signal when registering them. Calling abort() removes listeners registered with that signal.

import { useEffect } from "react";

function EscapeListener() {
  useEffect(() => {
    const controller = new AbortController();

    function handleKeyDown(event) {
      if (event.key === "Escape") {
        console.log("Escape pressed");
      }
    }

    window.addEventListener("keydown", handleKeyDown, {
      signal: controller.signal
    });

    return () => {
      controller.abort();
    };
  }, []);

  return <p>Press Escape to trigger the listener.</p>;
}

export default EscapeListener;

This approach is useful when one controller manages several listeners. For a single listener, calling removeEventListener() directly is also a valid and straightforward cleanup strategy.

15. Common Mistakes and Their Solutions

Mistake Problem Solution
Adding listeners during rendering A new listener may be registered on every render. Use JSX event props or an Effect for external subscriptions.
Not removing listeners Listeners may remain active when no longer needed. Return a cleanup function.
Using a different handler in cleanup The original listener is not removed. Reuse the same function reference.
Ignoring dependencies The handler may use outdated values. Declare the reactive dependencies correctly.
Using onClick={handleClick()} The handler runs while rendering. Use onClick={handleClick}.
Registering global listeners for simple buttons Code becomes more complex than necessary. Prefer React's built-in event props.
Calling preventDefault() in a passive listener The browser will not allow that default action to be cancelled. Do not use passive mode when cancellation is required.
Ignoring Strict Mode checks Missing cleanup may lead to duplicate subscriptions during development. Ensure setup and cleanup correctly mirror each other.

16. Best Practices for Managing Event Listeners

  • Prefer React event props for normal interactions with JSX elements.
  • Use useEffect() for browser-level and external event subscriptions.
  • Always clean up listeners when they are no longer needed.
  • Use the same event type and handler reference when removing a listener.
  • Include all reactive dependencies used by the Effect.
  • Avoid creating unnecessary global listeners.
  • Use passive listeners for suitable high-frequency events when the handler does not need to cancel default browser behaviour.
  • Keep event handlers focused and easy to understand.
  • Test components that mount, update, and unmount to confirm that subscriptions behave correctly.
  • For scroll and pointer events that trigger expensive work, consider throttling, debouncing, or scheduling updates appropriately.
  • Do not manipulate React-managed DOM unnecessarily when state and JSX can represent the same UI.

17. Practical Project: Keyboard Shortcut Listener

Objective: Build a React component that listens for the Escape key and displays a message when the key is pressed.

import { useEffect, useState } from "react";

function KeyboardShortcut() {
  const [message, setMessage] = useState("Press Escape");

  useEffect(() => {
    function handleKeyDown(event) {
      if (event.key === "Escape") {
        setMessage("Escape key detected!");
      }
    }

    window.addEventListener("keydown", handleKeyDown);

    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, []);

  return (
    <div>
      <h2>Keyboard Shortcut Demo</h2>
      <p>{message}</p>
      <button onClick={() => setMessage("Press Escape")}>
        Reset
      </button>
    </div>
  );
}

export default KeyboardShortcut;

Project steps

  1. Create a React application or open an existing project.
  2. Create a component named KeyboardShortcut.
  3. Import useEffect and useState.
  4. Register a keydown listener inside the Effect.
  5. Update the message when the Escape key is pressed.
  6. Remove the listener in the cleanup function.
  7. Test the component by pressing Escape and using the Reset button.

18. Frequently Asked Interview Questions

Q1. What is an event listener?

An event listener is a function registered to run when a specified event occurs, such as a click, key press, or window resize.

Q2. What is addEventListener()?

It is a JavaScript method used to register a handler for a specific event on an event target.

Q3. What is removeEventListener()?

It removes a previously registered event listener when the event type, function reference, and capture setting match.

Q4. Why use useEffect() for native event listeners?

It provides a lifecycle for setting up external subscriptions and cleaning them up when dependencies change or the component is removed.

Q5. Should every React button use addEventListener()?

No. Use JSX event props such as onClick for ordinary interactions with React-rendered elements.

Q6. What happens if a listener is not removed?

It may continue responding to events when it is no longer needed, causing duplicate actions or unnecessary work.

Q7. Why must the same handler reference be used during cleanup?

The browser identifies the registered listener by its event type, callback reference, and capture setting. A new anonymous function is not the same callback.

Q8. What is the purpose of the cleanup function in useEffect()?

It reverses the setup operation, such as removing an event listener or disconnecting from an external system.

Q9. What is a passive event listener?

A passive listener indicates that its handler will not cancel the event's default behaviour using preventDefault().

Q10. How does React Strict Mode help identify listener problems?

In development, Strict Mode performs an extra Effect setup-and-cleanup cycle to help expose missing or incorrect cleanup logic.

19. Revision Checklist

  • Understand browser events and event listeners.
  • Know the difference between React event props and native event listeners.
  • Understand addEventListener() and removeEventListener().
  • Register global listeners inside an appropriate Effect.
  • Use cleanup functions to remove obsolete listeners.
  • Understand dependency arrays and stale values.
  • Practise keyboard, resize, scroll, and click examples.
  • Understand options such as once, capture, and passive.
  • Know how to prevent duplicate subscriptions.
  • Test listener behaviour when components mount, update, and unmount.

20. Conclusion

Managing event listeners is an essential skill for building reliable React applications. React's JSX event props are generally the best choice for standard UI interactions, while native listeners are valuable for global browser events and external systems. When using native listeners, register them at the appropriate time, maintain correct dependencies, and remove them through cleanup to avoid duplicate subscriptions and unexpected behaviour.

Continue learning React JS: JustAcademy React JS Training | Register for React JS Course Demo

Previous Next
whatsapp