# useMemo vs useCallback vs React.memo

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

- Difficulty: intermediate
- Tags: useCallback, useMemo, useState, memo
- Estimated time: 20 minutes
- Tests: 5
- Requires subscription: yes

## 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.
- The result of the expensive operation should remain constant across re-renders.
- One of the buttons (the memoized one) should skip re-rendering when the counter updates.
- The `Button` component should receive an object prop (`id`) alongside its callback prop.
- `React.memo` alone must not be enough: the object and callback props must also be stabilized (with `useMemo` and `useCallback`) for the memoized button to skip re-rendering.


## 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.
- `React.memo` only shallow-compares props, so inline objects and inline functions still trigger re-renders.
- Use `useMemo` to keep the object prop stable and `useCallback` to keep the callback prop stable.
- Ensure that only components affected by state changes re-render.


## Tests

01. increments normal count on Button click
02. increments count using MemoButton click
03. calls expensiveOperation only once
04. renders memoized expensive operation result
05. memoized button skips re-rendering when the count updates

