advice on using react memoization: useMemo, useCallback

I like the "new" react beta docs, lots more info, real helpful info. Well written, good examples, lots of details. Helping me learn & improve.

The docs have very helpful guidance for useMemo and when to use

  • use useMemo to cache expensive calculations, don't use for non expensive calculations
  • "In general, unless you’re creating or looping over thousands of objects, it’s probably not expensive"
  • if "time adds up to a significant amount (say, 1ms or more), it might make sense to memoize that calculation" I like the example they show for taking measurements.
Why? blanket use of useMemo (or useCallback) is not harmful but the "code becomes less readable", it also adds to cognitive overhead and does add another function.

"Optimizing with useMemo is only valuable in a few cases"

  • the calculation is noticeably slow and dependencies rarely change
    • you should know it's slow before you optimize with useMemo
    • check your dependencies, log every time the useMemo is regenerated, I've seen useMemo usages which were pointless because a dependency changed so often.
  • you pass as a prop to a component wrapper in memo
  • the value is a dependency of some hook


The docs have similar guidance which can be applied to useCallback, which is also a memoization. In many cases you don't need it. Again the docs call out a few use cases for useCallback:

  • you pass to a component wrapped in memo
  • the useCallback result is a dependency to another hook
  • if you’re writing a custom Hook, it’s recommended to wrap any functions that it returns into useCallback


Comments

Popular posts from this blog

deep dive into Material UI TextField built by mui

angular js protractor e2e cheatsheet

react-router v6.4+ loaders, actions, forms and more