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:
Contact Us