When to use useMemo and useCallback for performance optimization?

847 Views Asked by At

Consider i got such example:

import React, { useMemo, useCallback } from 'react'

const Hello = (props) => {
  const { firstName, lastName } = props
  const fullName = useMemo(() => `${firstName} ${lastName}`, [firstName, lastName])

  const sayHello = useCallback(() => {
    console.log(`Hello, ${fullName}`)
  }, [fullName])

  return (
    // ...
  )
}

export default Hello

Basically i have a component called Hello, and it receives two props firstName and lastName, then i need to calculate fullName based on those two props and has a function sayHello() uses fullName to do something

So my question is: In here is it necessary to use useMemo() and useCallback() for performance optimization? It seems like its kind of overuse of useMemo() and useCallback() for just a little benefit, and i am not sure if this might cause potential side effects?

1

There are 1 best solutions below

2
On BEST ANSWER

In that example, different answers for that use of useMemo and that use of useCallback:

  • The useMemo is almost certainly overkill; it's just not that expensive for sayHello to build that string (vs. creating a new function to pass to useMemo on every render).

  • The answer for useCallback depends on how sayHello is used. If sayHello is supplied as a prop to a component that is memoized on that prop (like a PureComponent, something that implements shouldComponentUpdate directly, or the result of wrapping a component with React.memo), it can be a performance optimization to keep sayHello stable by memoizing it as you've shown so that the component(s) you're passing it to don't have to re-render when it changes. If not, though, it's probably not useful, no.

I agree with Drew Reese: Start simple by just writing your functions, and then apply optimization to code you see performing poorly. (Although there are some situations where you might be proactive based on previous experience — say, passing a callback you could memoize to a couple of hundred pure child components...)