Empty Array: Run Once on Mount
What you'll learn: How to make your effect run exactly once when the component first appears, using an empty dependency array.
The Problem with Default Behavior
Remember that by default, useEffect runs after every render. But what if you have a side effect that should only happen once—when the component first mounts? Maybe you're fetching initial data, setting up a subscription, or logging an analytics event. Running these repeatedly would be wasteful or even create bugs.
The Empty Array Solution
Pass an empty array [] as the second argument to useEffect:
useEffect(() => {
console.log('This runs once on mount');
// Fetch data, set up subscription, etc.
}, []);
The empty array tells React: "This effect depends on nothing." Since it has no dependencies, React concludes there's never a reason to re-run it after the initial mount.
How It Works
When your component first renders and commits to the DOM, React runs the effect. On subsequent re-renders (from state changes, prop updates, etc.), React checks the dependency array. Since it's empty, React knows none of the effect's dependencies changed—because there are no dependencies—so it skips running the effect.
Common Use Cases
- Fetching data once when a page loads
- Starting a timer or interval that runs throughout the component's lifetime
- Subscribing to external services (WebSockets, browser events)
- Logging that a component mounted
Key Takeaway: An empty dependency array [] makes your effect run only once after the component mounts, perfect for initialization tasks that shouldn't repeat on every render.