1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Dependency Array
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
15Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Dependency Array

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
15Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

Dependency Array

Overview

By default, the useEffect hook runs after the initial render AND after every single subsequent re-render of the component. If a component re-renders 50 times, the effect runs 50 times. This is almost never what you want (e.g., you don't want to fetch user data from the API 50 times).

To control exactly when the effect runs, you must pass a second argument to useEffect: the Dependency Array.

The dependency array is a list of state variables or props that the effect 'depends' on. React will look at this array before running the effect. If none of the variables in the array have changed since the last render, React skips the effect entirely, saving massive amounts of processing power and network bandwidth.

Syntax

The 3 Modes of the Dependency Array
javascript
// Mode 1: NO Array (Runs on EVERY render) - Very Rare
useEffect(() => { console.log('Runs constantly!'); });

// Mode 2: EMPTY Array (Runs EXACTLY ONCE on mount) - Very Common
useEffect(() => {
  console.log('Component Loaded! Fetching initial data...');
}, []); 

// Mode 3: POPULATED Array (Runs on mount AND when dependencies change) - Very Common
useEffect(() => {
  console.log('The User ID changed! Fetching new user data...');
}, [userId]);

Common Pitfalls

  • The Infinite Loop of Death: If you call a state setter (e.g., setCount) inside a useEffect that has NO dependency array, you create an infinite loop. The effect updates state -> State triggers a re-render -> Re-render triggers the effect -> Effect updates state. Your browser will freeze and crash. Always use a dependency array.
  • The Stale Closure (Missing Dependencies): If your effect uses a state variable (e.g. userId), but you FORGET to put userId in the dependency array [], your effect will be trapped in a 'stale closure'. It will permanently use the very first userId value it saw, completely ignoring future updates. If you use it inside the effect, you MUST list it in the array.

Interview Questions

How do you make a useEffect run exactly once when a component loads?

You pass an empty array [] as the second argument. This tells React that the effect depends on absolutely nothing. Because 'nothing' can never change, React runs it once on the initial mount and never runs it again.

What does the exhaustive-deps ESLint rule do?

The react-hooks/exhaustive-deps rule strictly enforces that every single prop, state, or function declared inside the component that is used inside the useEffect block must be explicitly listed in the dependency array. This prevents insidious stale closure bugs.

Real-World Example

Syncing with a Specific Prop: If a user is viewing Profile #1, and clicks a link to view Profile #2, the component doesn't unmount. The parent simply passes a new userId prop. By listing userId in the dependency array, React automatically detects the change and re-runs the API fetch for the new user.

example
javascript
function UserProfile({ userId }) {
  const [userData, setUserData] = useState(null);

  // This effect will run on the very first load, 
  // AND anytime the parent passes down a NEW userId.
  useEffect(() => {
    // Only runs when 'userId' changes!
    async function fetchNewUser() {
      const response = await fetch(`/api/users/${userId}`);
      setUserData(await response.json());
    }
    fetchNewUser();

  }, [userId]); // <- The Dependency Array

  if (!userData) return <Loading />;
  return <div>{userData.name}</div>;
}

Check Your Knowledge

Test your understanding of Dependency Array with these quick questions.

Question 1

Which syntax guarantees a `useEffect` will only ever run exactly once (when the component mounts)?

Question 2

What will happen if an effect sets state, but has NO dependency array (e.g. `useEffect(() => setState(x))` )?

Take React Quiz
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

Dependency Array

Overview

By default, the useEffect hook runs after the initial render AND after every single subsequent re-render of the component. If a component re-renders 50 times, the effect runs 50 times. This is almost never what you want (e.g., you don't want to fetch user data from the API 50 times).

To control exactly when the effect runs, you must pass a second argument to useEffect: the Dependency Array.

The dependency array is a list of state variables or props that the effect 'depends' on. React will look at this array before running the effect. If none of the variables in the array have changed since the last render, React skips the effect entirely, saving massive amounts of processing power and network bandwidth.

Syntax

The 3 Modes of the Dependency Array
javascript
// Mode 1: NO Array (Runs on EVERY render) - Very Rare
useEffect(() => { console.log('Runs constantly!'); });

// Mode 2: EMPTY Array (Runs EXACTLY ONCE on mount) - Very Common
useEffect(() => {
  console.log('Component Loaded! Fetching initial data...');
}, []); 

// Mode 3: POPULATED Array (Runs on mount AND when dependencies change) - Very Common
useEffect(() => {
  console.log('The User ID changed! Fetching new user data...');
}, [userId]);

Common Pitfalls

  • The Infinite Loop of Death: If you call a state setter (e.g., setCount) inside a useEffect that has NO dependency array, you create an infinite loop. The effect updates state -> State triggers a re-render -> Re-render triggers the effect -> Effect updates state. Your browser will freeze and crash. Always use a dependency array.
  • The Stale Closure (Missing Dependencies): If your effect uses a state variable (e.g. userId), but you FORGET to put userId in the dependency array [], your effect will be trapped in a 'stale closure'. It will permanently use the very first userId value it saw, completely ignoring future updates. If you use it inside the effect, you MUST list it in the array.

Interview Questions

How do you make a useEffect run exactly once when a component loads?

You pass an empty array [] as the second argument. This tells React that the effect depends on absolutely nothing. Because 'nothing' can never change, React runs it once on the initial mount and never runs it again.

What does the exhaustive-deps ESLint rule do?

The react-hooks/exhaustive-deps rule strictly enforces that every single prop, state, or function declared inside the component that is used inside the useEffect block must be explicitly listed in the dependency array. This prevents insidious stale closure bugs.

Real-World Example

Syncing with a Specific Prop: If a user is viewing Profile #1, and clicks a link to view Profile #2, the component doesn't unmount. The parent simply passes a new userId prop. By listing userId in the dependency array, React automatically detects the change and re-runs the API fetch for the new user.

example
javascript
function UserProfile({ userId }) {
  const [userData, setUserData] = useState(null);

  // This effect will run on the very first load, 
  // AND anytime the parent passes down a NEW userId.
  useEffect(() => {
    // Only runs when 'userId' changes!
    async function fetchNewUser() {
      const response = await fetch(`/api/users/${userId}`);
      setUserData(await response.json());
    }
    fetchNewUser();

  }, [userId]); // <- The Dependency Array

  if (!userData) return <Loading />;
  return <div>{userData.name}</div>;
}

Check Your Knowledge

Test your understanding of Dependency Array with these quick questions.

Question 1

Which syntax guarantees a `useEffect` will only ever run exactly once (when the component mounts)?

Question 2

What will happen if an effect sets state, but has NO dependency array (e.g. `useEffect(() => setState(x))` )?

Take React Quiz

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A