React - Memo (Cache)

React - Memo (Cache)

About

Memoization is a React caching function that caches a computed value.

It

  • save the results of computation,
  • and reuse these results if it sees the same inputs later.

React memo is the equivalent of shouldComponentUpdate for a class component.

Usage

It will:

  • skip:
    • re-rendering when the props of a wrapped component are the same
    • computation when the dependency parameters of the memo function are the same
  • return the same reference to:
    • be able to test for equality.
    • not-recompute. If you compute data to be rendered, React will not re-render if the data is the same. (Not that an array or object creation will create each time another reference and will not be the same).

Example Usage

React.Memo wrapping a component

It's a higher-order component React.memo(), meaning it wraps a component

export default React.memo(function myFunctionComponent(props: any): any {
  // big computation
  return ();
});

UseMemo wrapping an object creation

  • Wrapping an array used as data
const sameReference = useMemo(()=>["element1","element2"], [])

UseState as Memo

If the function does not have any dependencies

const [helloWorld] = useState(() => return "Hello World")





Discover More
React - Caching

This article is caching functionalities in React. There are 2 caching functionalities: for computed values, you would use a memo for a prop function, you would use useCallback. If you pass a function...



Share this page:
Follow us:
Task Runner