useMemo
- Memoizes a value.
- Runs the factory function only when dependencies change.
const sum = useMemo(() => a + b, [a, b]);
useCallback
- Memoizes a function.
- Useful when passing callbacks to children or hooks.
const handleClick = useCallback(() => {
console.log("Clicked!");
}, []);
Difference
-
useMemo = “cache the result of this function”
-
useCallback = “cache the function itself”
Analogy
-
useMemo: bake the pie once and reuse the pie.
-
useCallback: save the recipe so you can reuse the same recipe card.
Top comments (0)