2

考虑我有这样的例子:

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

基本上我有一个名为的组件Hello,它接收两个道具firstNamelastName然后我需要fullName根据这两个道具进行计算,并有一个函数sayHello()用来fullName做某事

所以我的问题是:这里有必要使用useMemo()useCallback()进行性能优化吗?这似乎是一种过度使用,useMemo()只是useCallback()为了一点好处,我不确定这是否会导致潜在的副作用?

4

1 回答 1

4

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...)

于 2020-11-26T10:32:34.690 回答