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
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 useReducer
instead of useState
and pass on the dispatch
method to child components
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With