Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I wrap all functions that defined in component in 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
   )
}
like image 669
Peter Avatar asked Jul 23 '19 04:07

Peter


1 Answers

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.

like image 77
Shubham Khatri Avatar answered Sep 24 '22 06:09

Shubham Khatri