CodeBlanks Logo Icon CodeBlanks

Dependency control

Learn when useMemo recomputes.

Dependency check

useMemo's dependency array says what should trigger a recompute. If any of [items, query] changes, React calls the function again.

Immutability is required: if you do items.push(newItem), React doesn't see a change (same reference). Instead, setItems(prev => [...prev, newItem]) creates a new array.

So state in React is always updated with new objects. Mutating the old object causes React to miss the change and some hooks to misbehave.

Object reference

In JavaScript, objects are compared by reference. [1,2] === [1,2] is false; two separate arrays are different objects. But const a = [1,2]; a === a is true; same object.

React uses this comparison: is a value in the dependency array the same reference as before or not? If same, cache is used; if different, recompute.

So when updating state, always create a new object. setUser({ '{ ...user, name: "Ayşe" }' }) makes a new object; React notices. user.name = "Ayşe" doesn't.

Practice Sort with useMemo

Complete the skeleton. Write a SortedNames component. Take ({ '{ names }' }). Compute sorted with useMemo(() => [...names].sort(), [names]). Inside <ul>, render sorted.map((n, i) => <li key={ '{ i }' }>{ '{ n }' }</li>). Export it.

Starter code

App.jsx
import { useMemo } from "react";

// Write the SortedNames component here

Sample solution

App.jsx
import { useMemo } from "react";

function SortedNames({ names }) {
  const sorted = useMemo(() => [...names].sort(), [names]);
  return (
    <ul>
      {sorted.map((n, i) => (
        <li key={i}>{n}</li>
      ))}
    </ul>
  );
}

export default SortedNames;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When does useMemo recompute?

  • Every render
  • In useEffect
  • When a dependency changes Correct answer
  • Never

Explanation: Only when a dependency changes.

2 Mutation

Question
Pushing to an array is ____; React doesn't notice it.
Answer
Pushing to an array is mutasyon; React doesn't notice it.

Explanation: Pushing is mutation.

3 Match the dependency check

Term Meaning
[items, query] deps
same ref cache
new ref recompute
push mutation

All lessons in Intermediate