Search code examples
reactjsreact-hooksreact-usememo

Which param triggered React.useMemo recalculation?


here is my React hooks code:

function calc_c({a,b}){
  //some long calculation that is based on a,b
}
function MyComponent(params){
  var a=calc_a(params)
  var a=calc_b(params)
  var c=React.useMemo(()=>calc_c({a,b},[a,b])
}

my question: how to I find out which of the params in [a,b] changed and caused the calls to calc_c

edit: I ended up using a generic version of skyboyer excelent answer:

export function useChanged(name,value){
  function print_it(){
    console.log('changed',name)
  }
  React.useMemo(print_it,[value])
}

Solution

  • It depends whether you ask for debugging purposes or you'd like to rely on that in your code(e.g. "if A is changed then return B, otherwise C")

    For both cases, there is no simple way to achieve. But work arounds would differ.

    Assume you just want to figure out why this is recalculated. Then just put bazillion

    useEffect(() => {
      console.log("a is changed");
    }, [a])
    

    One per each dependency. Yes, boring and repetitive. But the simplest approach is, the less you should actually worry about additionally. Or take a look if useWhatChaged works to you(if there are literally dozen variables in dependency list).

    Another thing, if you would like to make check(but why?) in your regular(not in temporary code for debugging purposes I mean). Then you might use usePrevious or write something similar.