Suggest an editImprove this articleRefine the answer for “Empty dependency array”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)If you pass an **empty dependency array** (`[]`) to `useEffect`, the effect runs **only once** - **after the first render** (that is, when the **component mounts**). **Key point:** if the effect returns a function, it is called only when the component unmounts.Shown above the full answer for quick recall.Answer (EN)Image## When an effect with an empty dependency array runs If you pass an **empty dependency array** (`[]`) to `useEffect`, the effect runs **only once** - **after the first render** (that is, when the **component mounts**). --- ### Example ```javascript import { useEffect } from "react"; function Example() { useEffect(() => { console.log("Effect ran once on mount"); }, []); // empty dependency array return <div>Example</div>; } ``` What happens: 1. The component first appears on the screen (mounts). 2. React renders its content. 3. After the render, React calls `useEffect`. 4. The effect will **never run again**, even if the component re-renders. --- ### Analogy with classes Such `useEffect(() => {...}, [])` is fully analogous to the method: ```javascript componentDidMount() { // called once on mount } ``` in a class component. --- ## Cleanup on unmount If the effect returns a function - it will be called **only when** the component **unmounts** (is removed from the screen). ```javascript useEffect(() => { console.log("Subscription set up"); return () => { console.log("Subscription removed"); }; }, []); ``` Order: 1. The component mounts → `console.log("Subscription set up")` runs. 2. The component is removed → `console.log("Subscription removed")` runs. --- ## Typical use cases for `[]` - Make an API request when the page loads - Attach an event listener (and unsubscribe on removal) - Set the page title (`document.title`) - Start a timer or animation once --- ## Summary | Dependency array | When the effect runs | |---|---| | `[]` | **Once on mount**, cleanup - **on unmount** | | `[a, b]` | On the first render and when `a` or `b` changes | | *no array* | After **every** render |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.