What are the dependencies in useEffect and why are they important? Last Updated : 28 Apr, 2025 Comments Improve Suggest changes Like Article Like 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( 'https://fakestoreapi.com/products' ) .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 Comment More infoAdvertise with us Next Article What are the dependencies in useEffect and why are they important? F faheemakt6ei Follow Improve Article Tags : Web Technologies ReactJS React-Questions React-Hooks Similar Reads What are Optional Dependencies and when should we use them ? Optional dependencies in Node.js offer a flexible way to enhance the functionality of a package or module by providing additional features or optimizations without being mandatory for its core functionality. In this article, we'll delve into what optional dependencies are, how they work, and when to 6 min read What are the rules of hooks in React, and why are they important? In React, hooks empower functional components to utilize state and incorporate other React functionalities seamlessly, enabling a more dynamic and concise development approach. Rules of Hooks in React:Only use hooks at the top level: This means don't use hooks inside loops, conditions, or nested fun 2 min read Difference Between useState and useEffect Hook in ReactJS ReactJS is the powerful JavaScript library used for building user interfaces especially single-page applications(SPAs). Two of the most commonly used hooks in React are useState and useEffect. These hooks make functional components more powerful by allowing them to manage the state and handle side e 3 min read Difference in behaviour of componentDidUpdate and useEffectHook with no dependency Array If you have Basic knowledge of React with class-based components and functional components with hooks then you know we can achieve some life cycle methods of class-based components with useEffect() hooks with its dependency array and return function. like the componentDidUpdate method, we can achiev 4 min read What's the concept of custom hooks, and why do we use them? Custom hooks in React are JavaScript functions that utilize built-in React hooks or other custom hooks to encapsulate reusable logic in functional components. They follow a naming convention where the function name starts with "use" (e.g., useCustomHook). Custom hooks allow users to abstract complex 3 min read Like