T

TechIdea

Ecosystem

Reactbeginner7 min read

Hook: useEffect

Learn how to use the useEffect Hook to run side effects like API fetching, timers, and manual DOM updates in your components.

Learning Goals

1
Understand the lifecycle phases of functional React components.
2
Run side effects like API calls or subscriptions using useEffect.
3
Manage the effect dependency array to control when code executes.
4
Clean up active timers or event listeners to prevent memory leaks.

The Core Concept

Most React components calculate UI from props and state. However, sometimes components need to interact with the outside world. These actions are called Side Effects. Examples include fetching data from an API, setting up timers, or manually editing metadata.

The useEffect hook allows you to run side effects. It takes a function containing the effect logic, and a second parameter called the Dependency Array. The dependency array tells React exactly when to run the effect: if empty [], it runs only once when the component mounts. If it contains variables [userId], the effect runs every time those variables change. Failing to supply a dependency array can trigger infinite render loops, crashing your app.

Visual guide

React hooks data flow

A simple original diagram to connect the lesson idea with real project flow.

Code & Implementation

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

export default function UserLoader() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // This effect runs once when the component mounts
    fetch('https://jsonplaceholder.typicode.com/users/1')
      .then(response => response.json())
      .then(data => {
        setUser(data);
        setLoading(false);
      });
  }, []); // Empty dependency array ensures it runs only once

  if (loading) return <p>Loading user profile...</p>;

  return (
    <div style={{ padding: '16px', border: '1px solid #eaeaea', borderRadius: '8px' }}>
      <h3>{user.name}</h3>
      <p>Email: {user.email}</p>
      <p>Company: {user.company.name}</p>
    </div>
  );
}

Expected Output

UI preview:
- Initially displays 'Loading user profile...'
- After fake API completes, displays user card with name, email, and company.

Automatic Timer Hook

Hands-on practice task

Required for Mastery

The Challenge

Write a React component that displays a countdown timer. Set up an interval inside useEffect that decrements a seconds state every second. Ensure you clean up the interval when the component is unmounted.

Helpful Hints

  • Set state const [seconds, setSeconds] = useState(10);.
  • Inside useEffect, use const id = setInterval(...).
  • Return a function () => clearInterval(id) to clean up the interval.

Quick Knowledge Check

Why does my useEffect run twice on page load?
In development mode, React's Strict Mode intentionally mounts and unmounts components twice to help you find bugs and memory leaks (such as missing cleanup functions).
How do I run an effect only when a specific state changes?
Place that state variable inside the dependency array, e.g. useEffect(() => { ... }, [searchQuery]);.

Continue Learning

Next steps after this lesson

Practice task

Write a React component that displays a countdown timer. Set up an interval inside useEffect that decrements a seconds state every second. Ensure you clean up the interval when the component is unmounted.

Ready to take action?

Supercharge your career workflows!

Discover free online utilities to format data, build job applications, and automate your productivity routine with TechIdea.

Growth Newsletter

Get practical AI tools, SEO tips, and growth guides weekly.

Join creators, students, and businesses scaling with TechIdea.