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
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
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
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?
How do I run an effect only when a specific state changes?
Continue Learning
Next steps after this lesson
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.
Supercharge your career workflows!
Discover free online utilities to format data, build job applications, and automate your productivity routine with TechIdea.