</>
Skip to content
React lessons (19/47)

React — useEffect

Basic useEffect

import { useEffect } from 'react';

function Timer() {
    const [seconds, setSeconds] = useState(0);

    useEffect(() => {
        document.title = `Timer: ${seconds}s`;
    });

    return <p>Seconds: {seconds}</p>;
}

useEffect with Dependencies

function User({ userId }) {
    const [user, setUser] = useState(null);

    useEffect(() => {
        fetchUser(userId).then(data => setUser(data));
    }, [userId]); // Only run when userId changes

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

    return <h1>{user.name}</h1>;
}

Cleanup Function

function Timer() {
    const [seconds, setSeconds] = useState(0);

    useEffect(() => {
        const interval = setInterval(() => {
            setSeconds(s => s + 1);
        }, 1000);

        // Cleanup function
        return () => clearInterval(interval);
    }, []);

    return <p>Seconds: {seconds}</p>;
}

Effect Dependencies

// Run once on mount
useEffect(() => {
    console.log('Component mounted');
}, []);

// Run on every render
useEffect(() => {
    console.log('Component rendered');
});

// Run when specific values change
useEffect(() => {
    console.log('Value changed:', value);
}, [value]);

useEffect Examples

// Data fetching
function UserProfile({ userId }) {
    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        setLoading(true);
        fetchUser(userId)
            .then(data => {
                setUser(data);
                setLoading(false);
            })
            .catch(err => {
                console.error(err);
                setLoading(false);
            });
    }, [userId]);

    if (loading) return <p>Loading...</p>;
    if (!user) return <p>User not found</p>;

    return (
        <div>
            <h2>{user.name}</h2>
            <p>{user.email}</p>
        </div>
    );
}

// Document title
function DocumentTitle({ title }) {
    useEffect(() => {
        document.title = title;
        return () => {
            document.title = 'My App';
        };
    }, [title]);

    return <h1>{title}</h1>;
}

// Window resize
function WindowSize() {
    const [size, setSize] = useState({
        width: window.innerWidth,
        height: window.innerHeight
    });

    useEffect(() => {
        const handleResize = () => {
            setSize({
                width: window.innerWidth,
                height: window.innerHeight
            });
        };

        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
    }, []);

    return <p>Window: {size.width} x {size.height}</p>;
}

Mini Practice

Write React code that:

  1. Uses useEffect for side effects
  2. Adds dependencies to useEffect
  3. Cleans up effects
  4. Fetches data with useEffect

Up Next

Next: Learn about useContext hook.

Related Topics

Frequently Asked Questions about useEffect

What is useEffect in React?

useEffect is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn useEffect?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn useEffect.

Why is useEffect important in React?

useEffect is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.