Loading

Quipoin Menu

Learn • Practice • Grow

react / useEffect Dependency Array
interview

Q1. What is the purpose of the dependency array in useEffect?
The dependency array tells React when to re-run the effect. It contains variables that the effect depends on. If any of these variables change between renders, the effect runs again. If the array is empty, the effect runs only once. If no array is provided, it runs after every render.

Q2. What happens if you specify the wrong dependencies?
If you omit a dependency that is used inside the effect, you may get stale values and bugs. The effect will not re-run when that dependency changes, leading to incorrect behavior. The React ESLint rules help catch missing dependencies.

Q3. How do you run an effect only once (on mount)?
Pass an empty dependency array: useEffect(() => { ... }, []). This tells React that the effect doesn't depend on any props or state, so it only runs after the first render. This is similar to componentDidMount.

Q4. How do you run an effect when specific state changes?
Include that state variable in the dependency array: useEffect(() => { ... }, [count]). The effect runs after the first render and whenever count changes. This is useful for side effects like fetching data based on an ID.

Q5. Can the dependency array contain functions or objects?
Yes, but be careful because functions and objects are recreated on every render, causing the effect to run unnecessarily. To avoid this, you can wrap functions in useCallback or use useMemo for objects to stabilize references.