DEV Community

vishwa v
vishwa v

Posted on

react-10

Understanding useMemo and React.memo in React

Performance optimization is important in React applications, especially when components re-render frequently. React provides two useful tools for optimization: useMemo and React.memo.

What is useMemo?
useMemo is a React Hook that caches the result of an expensive calculation and recalculates it only when its dependencies change.

Why use useMemo?

Imagine your component performs a complex calculation every time it renders.

When to use useMemo

  • Expensive calculations
  • Large data filtering or sorting
  • Preventing unnecessary object or array recreation
  • Optimizing derived state

What is React.memo?

React.memo is a Higher-Order Component (HOC) that prevents unnecessary re-rendering of a component when its props haven't changed.

When to use React.memo

  • Pure functional components
  • Components receiving unchanged props frequently
  • Large UI trees
  • Expensive rendering logic

diff blw use memo and react memo

Feature useMemo React.memo
Purpose Memoize a value Memoize a component
Optimizes Calculations Component rendering
Type Hook Higher-Order Component
Used Inside Component Yes No
Returns Cached value Optimized component

Top comments (0)