React Performance Optimization: Memoization and Keys

React is fast, but you can make it faster. Here are the optimization techniques I use most often.

React.memo

const ExpensiveComponent = React.memo(function Expensive({ data }) {
  // Only re-renders if data changes
  return <div>{heavyCalculation(data)}</div>;
});

useMemo

function DataTable({ items, filter }) {
  const filtered = useMemo(() => {
    return items.filter(item => item.matches(filter));
  }, [items, filter]);  // Only recalculate when deps change
}

useCallback

function Parent() {
  const handleClick = useCallback(() => {
    doSomething();
  }, []);  // Stable reference
  
  return <Child onClick={handleClick} />;
}

Keys in Lists

// Bad - index as key
items.map((item, i) => <Item key={i} />);

// Good - stable unique key
items.map(item => <Item key={item.id} />);

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.