← Back to React Testing Library Mastery
Advanced16 min read

Performance Testing

Detect unnecessary re-renders and validate memoization in components.

Render Count Tracking

Spy on console or use @testing-library/react-hooks with render counter wrapper component. Assert child render count stable when parent re-renders with same props.

React DevTools Profiler API experimental in tests—prefer explicit render count mock for stability.

const renderSpy = jest.fn();
jest.mock("./ExpensiveChild", () => ({
  ExpensiveChild: (props) => {
    renderSpy();
    return <div {...props} />;
  },
}));

Profiling Components

React.Profiler onRender callback counts commits in integration test. Set baseline threshold—not flaky microsecond timing.

Performance tests belong in dedicated spec file run less frequently if slow.

  • Do not over-optimize for test environment unlike production
  • memo and useMemo validated by prop change causing single necessary render
  • Context changes re-render all consumers—split contexts to reduce blast radius

Memoization Tests

Pass new object literal prop each render—expect memoized child not to re-render if shallow compare works. Change meaningful prop—expect re-render.

Tests document intended memo contract for future refactors.

const { rerender } = render(<Parent value={1} />);
expect(renderSpy).toHaveBeenCalledTimes(1);
rerender(<Parent value={1} />);
expect(renderSpy).toHaveBeenCalledTimes(1);
rerender(<Parent value={2} />);
expect(renderSpy).toHaveBeenCalledTimes(2);

Optimization Verification

Virtualized lists: assert row count in DOM limited while data large—mock intersection observer. Debounce: use fake timers verify API not called until delay.

Avoid benchmarking absolute ms in jsdom—environment noisy.

  • Use userEvent with delay null for perf-sensitive test suites locally
  • Large RTL suites: split files for Jest parallel workers
  • Profile production builds separately from RTL unit tests

Limits of RTL Performance Tests

jsdom not real browser layout engine—use Playwright performance marks for real user metrics. RTL tests guard against accidental render loops not measure Core Web Vitals.

Treat render count tests as regression guards when team previously fixed specific bug.

  • React Strict Mode double render expected in dev tests
  • Delete perf tests that fail randomly without actionable fix
  • Pair with Lighthouse CI for page-level performance budgets

Get In Touch


Ready to discuss your next project? Drop me a message.