React Native theorytheory 0/50 · 0%
Performance · medium

21. useMemo and useCallback

Memoizing values and functions to avoid unnecessary work.

`useMemo` caches a computed value between renders unless its dependencies change; `useCallback` caches a function reference, which matters when passing callbacks to memoized children like a `FlatList` row.

import { useMemo, useCallback } from "react";

function TxSummary({ txs }: { txs: { amount: number }[] }) {
  const total = useMemo(() => txs.reduce((s, t) => s + t.amount, 0), [txs]);
  const onPressRow = useCallback((id: string) => console.log(id), []);
  return <Text>Total: {total}</Text>;
}

Don't memoize everything reflexively — memoization itself has a cost, and for cheap computations it can make code slower and harder to read for no benefit.

Check your understanding

  1. 1. What does useMemo cache?

  2. 2. What does useCallback cache?

  3. 3. Is it always beneficial to memoize?