React Performance Optimization Techniques

React Performance Optimization Techniques

React Performance Optimization

Performance is crucial for user experience. Here are techniques I use to keep React apps fast.

Measuring First

Before optimizing, measure! Use React DevTools Profiler and Chrome DevTools to identify actual bottlenecks.

Key Techniques

1. Memoization

Use React.memo for components that render often with the same props:

const ExpensiveComponent = React.memo(({ data }) => {
  // Only re-renders when data changes
  return <div>{/* complex rendering */}</div>;
});

2. useMemo and useCallback

Prevent unnecessary recalculations and function recreations:

const sortedData = useMemo(() => {
  return data.sort((a, b) => a.value - b.value);
}, [data]);

const handleClick = useCallback(() => {
  doSomething(id);
}, [id]);

3. Code Splitting

Split your bundle to load only what's needed:

const HeavyComponent = lazy(() => import('./HeavyComponent'));

function App() {
  return (
    <Suspense fallback={<Loading />}>
      <HeavyComponent />
    </Suspense>
  );
}

4. Virtual Lists

For long lists, render only visible items:

import { FixedSizeList } from 'react-window';

<FixedSizeList
  height={500}
  itemCount={10000}
  itemSize={50}
>
  {Row}
</FixedSizeList>

Common Pitfalls

  • Creating objects/arrays in render
  • Not using keys properly in lists
  • Over-using context for frequently changing values
  • Premature optimization

Remember: measure, optimize, measure again.