Should I wrap all functions that defined in component in useCallback?

删除回忆录丶 提交于 2021-02-18 21:57:40

问题


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

回答1:


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.

Using useCallback should be preferred in the following cases

  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

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

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.



来源:https://stackoverflow.com/questions/57156582/should-i-wrap-all-functions-that-defined-in-component-in-usecallback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!