UseEffect Hook with Dependency Array 2025

React useEffect Dependency Array (2025)

useEffect hook allows you to perform side effects in functional components. The dependency array tells React when to re-run the effect.

📌 No Dependency Array

This will run on every render:


useEffect(() => {
  console.log("Runs after every render");
});
  

✅ Empty Dependency Array

This will run only once after the initial render (componentDidMount):


useEffect(() => {
  console.log("Runs only once on mount");
}, []);
  

🔁 With Specific Dependencies

This will run when the value of count changes:


useEffect(() => {
  console.log("Count changed:", count);
}, [count]);
  

🧠 Real-Life Example

Suppose you want to fetch data when a search term changes:


useEffect(() => {
  fetch(`https://api.example.com/search?q=${query}`)
    .then(res => res.json())
    .then(data => setResults(data));
}, [query]);
  

✅ Always include all variables used inside useEffect in its dependency array unless you know what you're doing.