JAVASCRIPT

Perform Side Effects and Cleanup with useEffect

Master the useEffect hook in React to perform side effects like event subscriptions, data fetching, or DOM manipulations, and manage their cleanup lifecycle for optimal performance.

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

function MouseTracker() {
  const [position, setPosition] = useState({ x: 0, y: 0 });

  useEffect(() => {
    const handleMouseMove = (event) => {
      setPosition({ x: event.clientX, y: event.clientY });
    };

    // Subscribe to mousemove event
    window.addEventListener('mousemove', handleMouseMove);

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

  return (
    <div style={{ border: '1px solid gray', padding: '20px' }}>
      <h1>Mouse Position:</h1>
      <p>X: {position.x}, Y: {position.y}</p>
      <p>Move your mouse over this area!</p>
    </div>
  );
}

export default MouseTracker;
How it works: The useEffect hook allows you to perform side effects in functional components, such as data fetching, subscriptions, or manually changing the DOM. Its second argument, the dependency array, controls when the effect runs. If an empty array `[]` is provided, the effect runs once after the initial render and its cleanup function runs only on unmount, making it suitable for setting up global event listeners or subscriptions that need to be torn down once. The returned cleanup function is crucial for preventing memory leaks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs