18

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
   )
}
Peter
  • 656
  • 1
  • 6
  • 14

2 Answers2

43

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.

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
1

Just adding another case to the above answer. Sometimes you might have a function with a heavy computing and you probably don't want it to calculate the result on every render so in that case you would also use useCallback

jon
  • 51
  • 3
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 02 '21 at 03:31
  • 1
    for heavy computing, you'd use `useMemo` not `useCallback` right – Embedded_Mugs Dec 12 '22 at 19:39
  • 1
    @Embedded_Mugs it depends. If you want to get a value back you need to use `useMemo` but if you just need to run a function then you would use `useCallback` – jon Dec 13 '22 at 23:40