mediumFrontend

What is the purpose of the `deps` array in `useEffect` and `useCallback`?

1.1k views
01

Understand the problem

This fundamental question covers a core concept for controlling hook execution and preventing stale closures.

hooksusestateusecallbackdependencies
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Deps drive re-runs
import { useState, useEffect, useCallback } from "react";

export default function App() {
  const [query, setQuery] = useState("react");
  const [runs, setRuns] = useState(0);

  // recreated only when 'query' changes (stable reference otherwise)
  const search = useCallback(() => "results for: " + query, [query]);

  useEffect(() => {
    setRuns((r) => r + 1);            // effect re-runs whenever search changes
  }, [search]);                       // search depends on query → exhaustive deps

  return (
    <div style={{ padding: 24, fontFamily: "system-ui" }}>
      <input value={query} onChange={(e) => setQuery(e.target.value)} />
      <p>{search()}</p>
      <small>effect runs: {runs}</small>
    </div>
  );
}
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.