0
0
ReactHow-ToBeginner · 3 min read

UseEffect with Empty Dependency Array in React Explained

In React, using useEffect with an empty dependency array [] runs the effect only once after the component mounts. This pattern is useful for running setup code like fetching data or subscribing to events just one time.
📐

Syntax

The useEffect hook takes two arguments: a function (the effect) and a dependency array. When the dependency array is empty [], the effect runs only once after the component first renders.

Parts explained:

  • useEffect(() => { ... }): The effect function to run.
  • []: Empty array means no dependencies, so run effect once.
javascript
useEffect(() => {
  // code to run once after mount
}, []);
💻

Example

This example shows a React component that logs a message once when it mounts using useEffect with an empty dependency array.

javascript
import React, { useEffect } from 'react';

function Welcome() {
  useEffect(() => {
    console.log('Component mounted');
  }, []);

  return <h1>Hello, React!</h1>;
}

export default Welcome;
Output
Hello, React! (and console logs 'Component mounted' once)
⚠️

Common Pitfalls

Common mistakes include:

  • Omitting the dependency array, causing the effect to run after every render.
  • Adding variables inside the effect without listing them in dependencies, which can cause stale data or missed updates.
  • Using an empty array but expecting the effect to run on updates, which it won't.

Always include dependencies if you want the effect to re-run when those values change.

javascript
import React, { useEffect, useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  // Wrong: effect runs only once, but uses count which changes
  useEffect(() => {
    console.log('Count is', count);
  }, []); // count missing in dependencies

  return <button onClick={() => setCount(count + 1)}>Increment</button>;
}

// Correct:
// useEffect(() => {
//   console.log('Count is', count);
// }, [count]);
📊

Quick Reference

UseEffect with empty dependency array cheat sheet:

  • [] means run once after mount.
  • Good for setup like fetching data or event listeners.
  • Does not run on updates or unmount.
  • To run on updates, list dependencies inside the array.

Key Takeaways

Use useEffect with an empty array [] to run code once after component mounts.
Omitting the dependency array causes the effect to run after every render, which can hurt performance.
Always list dependencies if you want the effect to re-run when those values change.
Empty dependency array effects do not run on updates or unmount.
Common use cases include fetching data or setting up subscriptions once.