#16useMemo vs useCallback vs React.memo
20min

Overview

Learn to prevent unnecessary renders with useMemo, useCallback, and React.memo in React.

Requirements

  • The app should render a counter that increments correctly from two different buttons.
  • The expensive operation should only run once, even after multiple renders.
  • One of the buttons should avoid re-rendering unnecessarily when the counter updates.
  • The result of the expensive operation should remain constant across re-renders.

Notes

  • The normal button and the memoized button should both increment the counter.
  • Console logs can help verify that re-renders happen only when needed.
  • The expensive operation must not be recalculated after the first render.
  • Ensure that only components affected by state changes re-render.

Tests

  1. increments normal count on Button click
  2. increments count using MemoButton click
  3. calls expensiveOperation only once
  4. renders memoized expensive operation result