DEV Community

Cathy Lai
Cathy Lai

Posted on

useMemo and useCallback Explained

useMemo

  • Memoizes a value.
  • Runs the factory function only when dependencies change.
const sum = useMemo(() => a + b, [a, b]);
Enter fullscreen mode Exit fullscreen mode

useCallback

  • Memoizes a function.
  • Useful when passing callbacks to children or hooks.
const handleClick = useCallback(() => {
  console.log("Clicked!");
}, []);
Enter fullscreen mode Exit fullscreen mode

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)