Most React performance tutorials end with the same bad advice: wrap everything in useMemo and useCallback and call it a day. If you have followed that advice, you have probably made your application slower. These hooks are not free. Each one allocates memory, compares dependencies, and stores cached values. Used without purpose, they become overhead instead of optimization.

Let’s strip this down to what actually matters.

What Each Hook Really Does

useMemo remembers a value. You hand it a function that does heavy work, and it returns the result. On the next render, if your dependencies have not changed, React skips the calculation and hands back the old result.

useCallback remembers a function. It does not run the function for you. It simply returns the same function instance between renders as long as its dependencies stay the same.

That is the entire difference. One caches a computed value. One caches a reference. Mixing these up leads to code that looks optimized but behaves identically to unwrapped code while costing extra memory.

Why Function Identity Breaks Your Tree

When a component re-renders, React executes the entire function body again. Every variable is recreated. Every inline function gets a brand new address in memory.

In JavaScript, two functions that contain the exact same logic are not equal. () => {} === () => {} evaluates to false. The same rule applies to objects and arrays. If your parent component defines handleSubmit and passes it to a child, that child receives a new prop on every single render. Even if the child is wrapped in React.memo, it cannot tell that the new function does the same thing as the old one. The reference changed, so the child re-renders.

This is the root problem useCallback was built to solve. It is not about speed. It is about stability.

When useMemo Earns Its Keep

You need useMemo when you are performing work that is objectively expensive and you can see a measurable lag.

Think about filtering a massive dataset. If you have a table with tens of thousands of rows and a search input, you might write something like this inside your component:

const visibleRows = rows.filter(r => r.name.includes(query));

Without useMemo, that loop runs on every render. If the user clicks a button that toggles a sidebar, the parent re-renders, and your filter runs again even though rows and query never changed. On a large dataset, that stutter is visible.

useMemo fixes this by pinning the result:

const visibleRows = useMemo(() => {
  return rows.filter(r => r.name.includes(query));
}, [rows, query]);

Now React only re-runs that filter when the dependencies actually change.

The same logic applies to complex mathematical calculations, transforming API responses into chart-friendly formats, or deriving state that would otherwise be recalculated constantly.

There is a second, less obvious use case. If you create an object or array locally and include it in a useEffect dependency array, you can accidentally trigger that effect on every render. Inline objects and arrays get new identities each time, so the effect sees a changed dependency and fires again. Memoizing that object with useMemo keeps the reference stable and lets your effect run only when the underlying data actually changes.

When useCallback Becomes Necessary

useCallback matters most when you are passing handlers into child components that are optimized with React.memo.

Imagine a parent component that holds a counter. It also renders an expensive child list:

function Parent() {
  const [count, setCount] = useState(0);
  
  const handleItemClick = (id) => {
    console.log(id);
  };
  
  return (
    <div>
      <button onClick={() => setCount(c + 1)}>{count}</button>
      <ExpensiveList onItemClick={handleItemClick} />
    </div>
  );
}

Every time count changes, Parent re-renders. A fresh handleItemClick is created. Because ExpensiveList receives a new prop reference, it re-renders too. If ExpensiveList is wrapped in React.memo, that memoization is completely wasted because the function prop changed.

useCallback preserves the reference:

const handleItemClick = useCallback((id) => {
  console.log(id);
}, []);

Now ExpensiveList only re-renders when it truly needs to.

Another critical situation involves useEffect. If an effect subscribes to a function defined inside your component, and that function changes identity every render, the effect will teardown and resubscribe repeatedly. Memoizing the function keeps the effect stable.

The Dependency Array Trap and Stale Closures

Both hooks rely on dependency arrays, and this is where most bugs hide.

Si vous omettez une variable du tableau de dépendances, votre fonction ou valeur mémoïsée capture une ancienne version de cette variable. Il s'agit d'une fermeture obsolète (stale closure). L'interface utilisateur peut afficher des données fraîches, mais votre callback consulte toujours un état datant de trois rendus précédents. La solution est simple mais facile à manquer lors des revues de code : incluez chaque valeur utilisée à l'intérieur du hook qui pourrait changer.

Exécutez la règle ESLint react-hooks/exhaustive-deps. Elle détectera les omissions évidentes. Mais ne la traitez pas comme un robot. Comprenez pourquoi chaque dépendance est importante.

Le coût caché de la sur-optimisation

Les débutants ont souvent tendance à protéger chaque fonction et chaque valeur avec ces hooks car cela semble plus sûr. Cette habitude finit par se retourner contre vous.

React doit stocker les valeurs mises en cache en mémoire. À chaque rendu, il doit parcourir votre tableau de dépendances et comparer chaque élément à l'aide de Object.is. Cette comparaison est peu coûteuse, mais elle n'est pas gratuite. Si vous enveloppez un gestionnaire d'événement trivial comme onClick={() => setOpen(true)} dans un useCallback, vous payez un coût en mémoire et en CPU pour éviter de créer une fonction dont l'allocation aurait été instantanée.

Les hooks ajoutent également du bruit. Le code enveloppé dans useMemo et useCallback est plus difficile à lire et à maintenir. Chaque tableau de dépendances est une potentielle fermeture obsolète qui ne demande qu'à vous piéger.

La véritable règle d'or est peu glorieuse mais efficace : écrivez d'abord du code simple. N'optimisez que lorsque vous avez la preuve d'un problème. Utilisez le React DevTools Profiler pour identifier quels composants sont coûteux et quels rendus sont inutiles. Si un rendu prend moins de quelques millisecondes, aucun utilisateur ne le remarquera, et votre mémoïsation ne résout rien.

L'essentiel

useMemo est destiné aux valeurs coûteuses. useCallback est destiné aux références de fonctions stables. Aucun de ces hooks ne rend votre composant plus rapide à rendre par lui-même ; ils empêchent un travail inutile en aval. Commencez sans eux, mesurez avec les outils appropriés, et ajoutez-les précisément là où le profiler indique un goulot d'étranglement. Un code propre qui se rerend occasionnellement l'emportera presque toujours sur un code sur-conçu qui mémoïse tout.