简体   繁体   中英

function prop as dependency for useCallback

I am not really sure when we should avoid using useCallback, if there is any harm (memory reallocation). For example lets say I have a component with two props, {onSave, onClose} and one sate viewName. is bellow handler function will be optimized with these dependencies?

  const handleSaveView = useCallback(() => {
    onSaveView(viewName, selectedViewList);
    onClose();
  }, [onSaveView, onClose, viewName]);

useCallback saves a function you pass to it and, in the future, returns that function instead of the new one if any of the values in the dependency array change.

This comes at a cost, mostly in the tests of the dependency array and, most of the time, it isn't worth using. It's a very tempting tool for premature optimization .

There are times when that cost is worth paying, such as when the function has an internal state or it is a dependency of another hook (so recreating the function would trigger the other hook to re-run).

Dmitri Pavlutin's "Your Guide to React.useCallback()" covers this in more depth.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM