我应该将组件中定义的所有函数都包装在 useCallback 中吗? [英] Should I wrap all functions that defined in component in useCallback?

查看:77
本文介绍了我应该将组件中定义的所有函数都包装在 useCallback 中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,React 函数组件中定义的函数会在组件重新渲染时重新生成.由于 useCallback 可以由特定依赖项触发,因此可以防止这些函数不必要的重新生成.我应该将它们中的每一个都包装在 useCallback 中,并传递相关的依赖项吗?

As far as I've known, functions that defined in a React's functional component are regenerated whenever the component rerenders. Since useCallback can be triggered by specific dependencies, it prevents unnecessary regeneration of these functions. Should I wrap each of them in useCallback, and pass relevant dependencies?

import React from 'react'

const Comp = () => {
   const fn1 = useCallback(
     ()=>{
      // do something
   }, [dependency1])

   const fn2 = useCallback(
     ()=>{
      // do something
   }, [dependency2])

   return (
      //something
   )
}

推荐答案

useCallback 将有助于避免在功能组件重新呈现时重新生成功能.然而,功能的重新创建并没有造成太大的性能差异.

useCallback will help in avoiding regeneration of functions when the functional component re-renders. However there isn't much of a performance difference caused by recreation of functions.

以下情况应优先使用useCallback

Using useCallback should be preferred in the following cases

  1. 如果您将函数作为 props 传递给子组件,并且子组件通常不需要重新渲染,除非某个 prop 更改,那么 useCallback 可能会阻止某些重新渲染.但是,如果您的状态很复杂,并且您需要将多个这样的函数作为道具传递给子级,最好转移到 useReducer 而不是 useState 并传递 dispatch 方法到子组件

  1. If you are passing the function on to child component as props and the child component doesn't often need re-rendering except when a certain prop change then useCallback might prevent certain re-renders. However if you state is complex and you need multiple such functions to be passed on to children as props, it better to shift to useReducer instead of useState and pass on the dispatch method to child components

您正在指定一个函数作为 useEffect 的依赖项.在这种情况下,您必须确保不会在每次渲染时重新创建该函数,否则 useEffect 将在每次渲染时触发.

You are specifying a function as a dependency to useEffect. In such as case you must ensure that the function in not recreated on every render or the useEffect will be triggered on every render.

总的来说,必须明智地而不是盲目地做出使用 useCallback 的决定,因为您可能会过度使用 useCallback 提供的优势,并最终降低性能,因为 useCallback 还会记住这些函数,并且频繁更改的依赖项可能无论如何都需要重新创建该函数.

Overall a decision to use useCallback must be made judiciously instead of blindly since you might just overdo the advantage offered by useCallback and end up degrading the performance since useCallback will also memoize the functions and a frequently changing dependency might anyways need to recreate the function.

这篇关于我应该将组件中定义的所有函数都包装在 useCallback 中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆