Open In App

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

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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?

  • Fetching Data: When you need to fetch data from an API or a server when the component mounts or when certain state variables change.
  • Subscriptions and Event Listeners: When you need to subscribe to events, such as keyboard events, window resizing, or WebSocket messages.
  • Manual DOM Manipulation: When you need to perform manual DOM manipulations, like changing the title of the page or adding/removing classes.
  • Clean-up Operations: When you need to perform clean-up operations, like unsubscribing from event listeners or canceling asynchronous tasks when the component unmounts or when certain dependencies change.

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.

  • Optimizes performance by running the effect only when necessary.
  • Prevents unnecessary re-renders, improving efficiency.
  • Ensures proper resource cleanup, preventing memory leaks.
  • Guarantees predictable behavior by indicating dependencies.
  • Assists in debugging by identifying missing or unnecessary dependencies.

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

Javascript




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:

gfg25

Output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads