简体   繁体   English

何时使用 useMemo 和 useCallback 进行性能优化?

[英]When to use useMemo and useCallback for performance optimization?

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基本上我有一个名为Hello的组件,它接收两个道具firstNamelastName ,然后我需要根据这两个道具计算fullName并有一个 function sayHello()使用fullName做某事

So my question is: In here is it necessary to use useMemo() and useCallback() for performance optimization?所以我的问题是:这里是否有必要使用useMemo()useCallback()进行性能优化? 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?似乎过度使用useMemo()useCallback()只是为了一点好处,我不确定这是否会导致潜在的副作用?

In that example, different answers for that use of useMemo and that use of useCallback :在该示例中,使用useMemo和使用useCallback的不同答案:

  • The useMemo is almost certainly overkill; useMemo几乎可以肯定是矫枉过正。 it's just not that expensive for sayHello to build that string (vs. creating a new function to pass to useMemo on every render). sayHello构建该字符串并没有那么昂贵(与创建一个新的 function 以在每次渲染时传递给useMemo )。

  • The answer for useCallback depends on how sayHello is used. useCallback的答案取决于sayHello的使用方式。 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.如果sayHello作为 prop 提供给在该 prop 上记忆的组件(例如PureComponent ,直接实现shouldComponentUpdate的东西,或者用React.memo包装组件的结果),它可以是保持sayHello稳定的性能优化通过记忆它,就像你展示的那样,你传递给它的组件在它发生变化时不必重新渲染。 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.我同意Drew Reese的观点:从编写你的函数开始,然后对你认为表现不佳的代码进行优化。 (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...) (尽管在某些情况下,您可能会根据以前的经验采取主动——例如,将一个回调传递给您可以记忆的几百个纯子组件……)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM