且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

React hooks 中的函数组件中的函数 - 性能

更新时间:2022-04-02 21:55:20

别担心

不要担心在每次渲染时创建新函数.只有在边缘情况下才会妨碍您的表现.设置 onClick 处理程序不是其中之一,因此只需在每次渲染时创建一个新函数即可.

Don't worry about it

Don't worry about creating new functions on each render. Only in edge cases does that impede your performance. Setting onClick handlers are not one of those, so just create a new function on each render.

然而,当你需要确保每次都使用相同的函数时,你可以使用 使用回调

However, when you need to make sure you use the same function every time, you can use useCallaback

这就是为什么您不应该为 onClick 处理程序(和大多数其他事件处理程序)使用 useCallback 的原因.

Here is a reason why you shouldn't bother with useCallback for onClick handlers (and most other event handlers).

考虑以下代码片段,其中一个没有 useCallback:

Consider the following code snippets, one without useCallback:

function Comp(props) {
  return <button onClick={() => console.log("clicked", props.foo)}>Text</Button>
}

和 useCallback 之一:

and one with useCallback:

function Comp(props) {
  const onClick = useCallback(() => {
    console.log("clicked", props.foo)
  }, [props.foo])

  return <button onClick={onClick}>Text</Button>
}

后者的唯一区别是 React 确实有如果 props.foo 保持不变,则更改按钮上的 onClick.改变回调是一个非常便宜的操作,而且根本不是值得让您的代码复杂化,以提高其理论性能.

The only difference in the latter is that React doen's have to change the onClick on your button if props.foo remains the same. Changing the callback is a very cheap operation, and it's not at all worth complicating your code for the theoretical performance improvement it gives.

另外,值得注意的是每次渲染时仍会创建一个新函数即使您使用 useCallback,但 useCallback 将返回旧的只要作为第二个参数传递的依赖项不变.

Also, it's worth noting that a new function is still created on every render even when you use useCallback, but useCallback will return the old one as long as the dependencies passed as the second argument are unchanged.

使用 useCallback 的意义在于,如果您将两个函数与引用进行比较等式,fn === fn2 只有当 fnfn2 指向内存中的同一个函数时才为真.功能是否相同并不重要.

The point of using useCallback is that if you compare two functions with reference equality, fn === fn2 is true only if fn and fn2 point to the same function in memory. It doesn't matter if the functions do the same.

因此,如果您有记忆或仅在函数更改时运行代码,使用 useCallback 再次使用相同的函数会很有用.

Thus, if you have memoisation or otherwise only run code when the function changes, it can be useful to use useCallback to use the same function again.

例如,React hooks 比较新旧依赖项,可能 使用 对象.是.

As an example, React hooks compare old and new dependencies, probably using Object.is.

另一个例子是 React.PureComponent,它只会在道具或状态已更改.这对于使用大量资源进行渲染的组件很有用.通过例如每次渲染时对 PureComponent 的新 onClick 将导致它每次重新渲染.

Another example is React.PureComponent, which will only re-render when props or state have changed. This can be useful for components that use a lot of resources to render. Passing e.g. a new onClick to a PureComponent on each render will cause it to re-render every time.