Hackforge Academy

Category: react

What Is the useEffect Dependency Array?

Published on 27 Oct 2026

Explanation

The dependency array tells React when an effect should run again. An empty array runs the effect after the component mounts, while dependencies make it rerun when their values change.

Code:

import { useEffect } from 'react';

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

useEffect(() => {
  console.log('Runs after mount');
}, []);

useEffect(() => {
  console.log('Runs when userId changes');
}, [userId]);

Explanation

Without a dependency array, the effect runs after every committed render. With an empty array, it runs after the initial mount, with an extra setup-and-cleanup cycle possible in development Strict Mode.

Code:

useEffect(() => {
  console.log('Every committed render');
});

useEffect(() => {
  console.log('Mount effect');
}, []);

Explanation

List every reactive value used by an effect in its dependency array. React compares each dependency with its previous value using Object.is.

Code:

useEffect(() => {
  document.title = `${firstName} ${lastName}`;
}, [firstName, lastName]);

Explanation

Objects and functions created during rendering get new identities on each render. If they appear in the dependency array, the effect can rerun even when their contents look unchanged.

Code:

const options = { roomId };

useEffect(() => {
  connect(options);
  return () => disconnect(options);
}, [options]); // New object on each render

Explanation

Do not silence dependency warnings just to stop an effect from rerunning. Restructure the effect, move constants outside the component, or create objects inside the effect so dependencies accurately represent what it uses.

Code:

useEffect(() => {
  const options = { roomId };
  const connection = connect(options);

  return () => connection.disconnect();
}, [roomId]);

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community