Open In App

What are the dependencies in useEffect and why are they important?

The useEffect hook in React is used for handling side effects in your components. Side effects are tasks that don’t directly relate to updating what the user sees on the screen, like fetching data from a server, subscribing to external events, or manually changing the DOM outside of React.

When to Use the useEffect Hook?

Importance of Dependencies in useEffect:

The useEffect hook accepts two arguments i.e. a function containing the code you want to run as a side effect, and an optional array of dependencies. The dependencies array allows you to specify which values the effect depends on. If any of these values change, the effect will be re-run.



Example: Below is an example of using the useEffect hook.




import React,
{
    useState,
    useEffect
} from 'react';
import axios from 'axios';
 
function CombinedExample() {
    const [data, setData] = useState(null);
    const [timer, setTimer] = useState(0);
 
    // Fetching data when the component mounts
    useEffect(() => {
        axios.get(
        )
            .then(response => setData(response.data))
            .catch(error =>
                console.error('Error fetching data:', error));
    }, []);
    /*
        Empty dependency array means this effect
        runs only once, when the component mounts
    */
 
    // Subscribing to keydown event
    useEffect(() => {
        const handleKeyPress = (event) => {
            console.log('Key pressed:', event.key);
        };
 
        window.addEventListener('keydown', handleKeyPress);
 
        return () => {
            window.removeEventListener('keydown', handleKeyPress);
        };
    }, []);
 
    // Changing the title of the page when the component mounts
    useEffect(() => {
        document.title = 'New Page Title';
    }, []);
 
    // Clean-up for timer
    useEffect(() => {
        const intervalId = setInterval(() => {
            setTimer(prevTimer => prevTimer + 1);
        }, 1000);
 
        return () => {
            // Clean up the interval when the component unmounts
            clearInterval(intervalId);
        };
    }, []);
 
    return (
 
        <div>
            <div>
                <p>Fetched Data:</p>
                <p>Timer: {timer}</p>
                {data ? (
                    <ul>
                        {
                            data.map(product => (
                                <li key={product.id}>
                                    <p>{product.title}</p>
                                    <p>Price: {product.price}</p>
                                    <p>
                                        Description:
                                        {product.description}
                                    </p>
                                </li>
                            ))
                        }
                    </ul>
                ) : (
                    <p>Loading...</p>
                )}
            </div>
 
        </div>
    );
 
}
 
export default CombinedExample;

Output:



Output


Article Tags :