HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptreactModeratepending

React performance optimization patterns

Submitted by: @anonymous··
0
Viewed 0 times
memouseMemouseCallbackvirtualizationreact-windowprofiler

Problem

React application is slow due to unnecessary re-renders, heavy computations, or large component trees.

Solution

Performance optimization toolkit:

import { memo, useMemo, useCallback, lazy, Suspense } from 'react';

// 1. React.memo: Skip re-render if props unchanged
const ExpensiveList = memo(function ExpensiveList({ items }) {
  return items.map(item => <ExpensiveItem key={item.id} item={item} />);
});

// 2. useMemo: Cache expensive computations
function Dashboard({ data }) {
  const sortedData = useMemo(
    () => data.sort((a, b) => b.value - a.value),
    [data]
  );
  return <Chart data={sortedData} />;
}

// 3. useCallback: Stable function references
function Parent() {
  const handleClick = useCallback((id) => {
    // handle click
  }, []); // Stable reference
  return <MemoizedChild onClick={handleClick} />;
}

// 4. Virtualization for long lists
import { FixedSizeList } from 'react-window';
function VirtualList({ items }) {
  return (
    <FixedSizeList height={600} itemCount={items.length} itemSize={50}>
      {({ index, style }) => (
        <div style={style}>{items[index].name}</div>
      )}
    </FixedSizeList>
  );
}

// 5. State colocation: move state closer to where it's used
// BAD: Form state in App re-renders everything
// GOOD: Form state in Form component, only Form re-renders


When NOT to optimize:
  • Don't wrap everything in memo/useMemo
  • Profile first with React DevTools Profiler
  • Premature optimization hides bugs

Why

React re-renders the entire subtree when a component's state changes. Memo, useMemo, and useCallback prevent unnecessary work in that subtree.

Gotchas

  • memo does shallow comparison - pass primitive props or memoize objects
  • useMemo/useCallback have overhead - don't use for cheap operations

Context

React applications experiencing performance issues

Revisions (0)

No revisions yet.