问题
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
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
useReducerinstead ofuseStateand pass on thedispatchmethod to child componentsYou 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 theuseEffectwill 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