React useEffect Hook

The useEffect hook is a powerful tool in React that allows you to handle side effects in functional components. It is used for operations such as fetching data, manually manipulating the DOM, subscribing to external data sources, and more.

1. Basic Syntax of useEffect

The basic syntax of the useEffect hook looks like this:

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

function ExampleComponent() {
    useEffect(() => {
        // Your side effect code here
    }, []); // Dependency array

    return (
        <div>
            <h1>Hello, React!<<h1>
        </div>
    );
}

In this example, useEffect runs after the first render of the component. The second argument is an empty array [], which means the effect will run only once when the component mounts.

2. Using useEffect for Data Fetching

Commonly, useEffect is used to fetch data when a component mounts. Here’s an example of how to fetch data from an API:

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

function FetchDataExample() {
    const [data, setData] = useState([]);
    
    useEffect(() => {
        fetch('https://jsonplaceholder.typicode.com/posts')
            .then(response => response.json())
            .then(data => setData(data))
            .catch(error => console.error('Error fetching data:', error));
    }, []); // Dependency array to run effect once on mount

    return (
        <div>
            <h1>Data:</h1>
            <ul>
                {data.map(item => (
                    <li key={item.id}>{item.title}</li>
                ))}
            </ul>
        </div>
    );
}

This example fetches a list of posts from the API and displays them in a list. The effect runs only once when the component mounts, ensuring the data is fetched only once.

3. Using useEffect with Dependencies

You can control when the effect should run by passing a dependency array as the second argument. The effect will run whenever any value in the array changes. Here’s an example:

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

function CounterComponent() {
    const [count, setCount] = useState(0);

    useEffect(() => {
        console.log('Count has changed:', count);
    }, [count]); // Effect runs when 'count' changes

    return (
        <div>
            <h1>Count: {count}</h1>
            <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
    );
}

In this example, the effect will run every time the count value changes. The console.log will be triggered whenever the count is updated.

4. Cleanup Function in useEffect

Some side effects require cleanup to avoid memory leaks or other unintended behavior, such as when setting up subscriptions or timers. You can return a cleanup function from the useEffect callback:

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

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

    useEffect(() => {
        const timer = setInterval(() => {
            setSeconds(prev => prev + 1);
        }, 1000);

        return () => clearInterval(timer); // Cleanup on unmount
    }, []); // Empty dependency array ensures effect runs once

    return (
        <div>
            <h1>Timer: {seconds} seconds</h1>
        </div>
    );
}

In this example, a timer is set up using setInterval, and the interval is cleared when the component unmounts to prevent memory leaks.

5. Summary

The useEffect hook is essential for handling side effects in functional components. It allows you to perform operations like data fetching, DOM manipulations, and more. You can also manage when effects run by using dependency arrays and perform cleanup when necessary.

Note: We aim to make learning easier by sharing top-quality tutorials, but please remember that tutorials may not be 100% accurate, as occasional mistakes can happen. Once you've mastered the language, we highly recommend consulting the official documentation to stay updated with the latest changes. If you spot any errors, please feel free to report them to help us improve.

top-home