Skip to main content

Command Palette

Search for a command to run...

useEffect in React.js [part-1]

Getting Started with useEffect in React.js

Updated
3 min read
useEffect in React.js [part-1]

Introduction

The useEffect hook in React lets you perform side effects in functional components, such as data fetching, subscriptions, or manually updating the DOM. It provides a way to synchronize your component with external systems after the rendering process is complete.

In simple terms, when your component first renders and shows to the user, you often need to fetch fresh data from an API or set up event listeners. But here's the problem: you can't just make an API call and update a regular variable - React won't know anything changed, so it won't update what the user sees.

This is where useEffect comes in. It lets you run code after your component renders. Inside useEffect, you can fetch data and update state using setState. When you update state, React detects the change and re-renders your component with the new data.

Think of it this way: useEffect is the designated place for 'side effects' - things like API calls, subscriptions, or timers that need to happen after rendering.


Syntax

  • Setup Function: Contains the core logic of your effect. React runs this function after the component renders and the DOM is updated.

  • Cleanup Function (optional): If your effect needs cleanup (e.g., stopping a timer, unsubscribing from an event), you return a function from the setup function. React runs this cleanup function before the component unmounts or before the effect runs again due to a dependency change.

  • Dependencies Array (optional): An array of values (props, state, etc.) that the effect depends on. The effect will re-run only when any value in this array changes.

  • Side effects are the ones which update the states.

  • Dependencies are the one when you want to run this side effects again when this dependency value is changed. It will run once if empty array is passed.

useEffect(() => {
  // Side effect code (setup function)

  return () => {
    // Cleanup function (optional)
  };
}, [dependencies]); // Optional dependency array

Example

Basic but production level example used by many products and teams. Set window size when it is changed (resized). If you not able to understand it is fine just notice the syntax.

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

const WindowTracker = () => {
  // 1. Initialize state to hold the window width
  const [windowWidth, setWindowWidth] = useState(window.innerWidth);

  useEffect(() => {
    // 2. Define the function to update state
    const handleResize = () => {
      setWindowWidth(window.innerWidth);
    };

    // 3. Setup: Add the event listener on mount
    window.addEventListener('resize', handleResize);

    // 4. Cleanup: This function runs when the component is destroyed (unmounted)
    // In production, always clean up subscriptions, timers, and listeners!
    return () => {
      window.removeEventListener('resize', handleResize);
    };

    // 5. Dependency Array: Empty [] means this effect runs ONCE on mount
  }, []); 

  return (
    <div style={{ padding: '20px', textAlign: 'center' }}>
      <h2>Window Width Monitor</h2>
      <p>The current width of your browser is: <strong>{windowWidth}px</strong></p>
    </div>
  );
};

export default WindowTracker;

Common Use Cases

  • Fetching Data: The most common use case is fetching data from an API when a component mounts or when a certain prop/state changes.

  • DOM Manipulation: Manually updating the DOM (e.g., setting the document title) when this cannot be done declaratively in the render phase.

  • Event Listeners/Subscriptions: Setting up and tearing down event listeners or subscriptions to external systems to prevent memory leaks.

Understanding useEffect in React.js Basics