← Back to all snippets
JAVASCRIPT

Managing Event Listeners with useEffect

Master `useEffect` in React to safely add and remove global event listeners, preventing memory leaks and ensuring proper resource management in your components.

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

function KeyboardListener() {
  const [keyPress, setKeyPress] = useState('');

  useEffect(() => {
    const handleKeyPress = (event) => {
      setKeyPress(`Last key pressed: ${event.key}`);
    };

    // Add event listener when component mounts
    window.addEventListener('keydown', handleKeyPress);

    // Cleanup function: Remove event listener when component unmounts
    return () => {
      window.removeEventListener('keydown', handleKeyPress);
    };
  }, []); // Empty dependency array means this effect runs once on mount and cleans up on unmount

  return (
    <div>
      <h2>Keyboard Event Listener</h2>
      <p>{keyPress || 'Press any key!'}</p>
    </div>
  );
}

export default KeyboardListener;
How it works: This code uses `useEffect` to manage a global keyboard event listener. When the component mounts, `window.addEventListener('keydown', handleKeyPress)` registers a function to capture key presses and update state. The crucial part is the `return` function within `useEffect`, which acts as a cleanup mechanism. It calls `window.removeEventListener('keydown', handleKeyPress)` when the component unmounts, preventing memory leaks and ensuring that the listener is properly disposed of.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs