Labs ICT
โญ Pro Login

useCallback Hook

Caching function references.

Caching Function References

The useCallback Hook caches a function definition between re-renders. In JavaScript, every time a component renders, it creates new function instances. This means if you pass a function as a prop to a memoized child component, the child re-renders even if its props haven't actually changed. useCallback gives you a stable function reference that only changes when its dependencies change.

Think of it like a saved contact in your phone. Instead of looking up the number every time you want to call, you just tap the saved contact. useCallback saves your function so you don't have to recreate it on every render. This is especially useful when passing functions to child components or using them in useEffect dependencies.

useCallback vs useMemo

These two Hooks are closely related but serve different purposes. useMemo caches a computed value - the result of running a function. useCallback caches the function itself. In fact, useCallback(fn, deps) is equivalent to useMemo(() => fn, deps). One caches values, the other caches functions.

function Parent() {
  const [count, setCount] = useState(0)
  const handleClick = useCallback(() => {
    console.log("Button clicked")
  }, [])
  return (
    <div>
      <p>{count}</p>
      <button onClick={() => setCount(c => c + 1)}>Increment</button>
      <MemoizedChild onClick={handleClick} />
    </div>
  )
}
Try it Yourself โ†’

Preventing Unnecessary Re-renders

The real power of useCallback shines when combined with React.memo. If a child component is wrapped in React.memo, it only re-renders when its props change. But if you're passing a new function on every render, the child sees a "new" prop and re-renders anyway. useCallback gives you a stable function reference, so the child only re-renders when the function's dependencies actually change.

This is one of those optimizations that seems small but can have a big impact in large applications with many re-rendering components. It's the difference between your app feeling snappy and feeling sluggish. The function reference stays the same, so child components don't waste time re-rendering.

When to Use useCallback

Use useCallback when you're passing functions as props to memoized child components. Use it when functions are dependencies in useEffect and you don't want the effect to re-run unnecessarily. Use it when you're creating callback functions that need stable references for event handlers in optimized components.

Don't use it everywhere though. If a function is only used locally and doesn't get passed as a prop or used as a dependency, useCallback adds overhead without benefit. The key is to measure and optimize where it actually makes a difference. Start simple, profile your app, and add memoization where you see real performance issues.

๐Ÿงช Quick Quiz

What is the useCallback hook for?