Maybe I misunderstood something, but useCallback Hook runs everytime when re-render happens.
I passed inputs - as a second argument to useCallback - non-ever-changea
One-liner for useCallback vs useMemo:
useCallback(fn, deps)is equivalent touseMemo(() => fn, deps).
With useCallback you memoize functions, useMemo memoizes any computed value:
const fn = () => 42 // assuming expensive calculation here
const memoFn = useCallback(fn, [dep]) // (1)
const memoFnReturn = useMemo(fn, [dep]) // (2)
(1) will return a memoized version of fn - same reference across multiple renders, as long as dep is the same. But every time you invoke memoFn, that complex computation starts again.
(2) will invoke fn every time dep changes and remember its returned value (42 here), which is then stored in memoFnReturn.
const App = () => {
const [dep, setDep] = useState(0);
const fn = () => 42 + dep; // assuming expensive calculation here
const memoFn = useCallback(fn, [dep]); // (1)
const memoFnReturn = useMemo(fn, [dep]); // (2)
return (
memoFn is {typeof memoFn}
Every call starts new calculation, e.g. {memoFn()} {memoFn()}
memoFnReturn is {memoFnReturn}
Only one calculation for same dep, e.g. {memoFnReturn} {memoFnReturn}
);
}
ReactDOM.render( , document.getElementById("root"));