Day 15: useCallback hook in react

Day 15: useCallback hook in react

Today is my 15th day of learning React js where I learned about the concept of useCallback hook in react, when it is used and when not to use it? Here's the summary of What I learned:


What is useCallback?

The useCallback hook is a performance optimization mechanism in React that helps prevent unnecessary re-renders of child components when their parent component re-renders. It achieves this by memoizing (caching) callback functions based on their dependencies. It preserves function across renders to prevent unnecessary re-renders. If the dependencies haven't changed, the same function reference is returned, avoiding the creation of a new function object on every render. It prevents infinite loops by maintaining function references.

When to Use useCallback:

  • Passing callbacks as props to child components: When a parent component passes a callback function as a prop to a child component, and the child component relies on the same callback reference across renders (e.g., for event handlers), useCallback can prevent the child from re-rendering unnecessarily due to a change in the parent's state or props.
  • Callbacks that are expensive to create: If creating the callback function involves complex calculations or fetching data, using useCallback can improve performance by ensuring it's only created when its dependencies change.

Example:

import React, { useState, useCallback } from 'react';        
function ParentComponent() {
  const [count, setCount] = useState(0);  const handleClick = useCallback(() => {
    setCount(count + 1);
  }, [count]); // Only recreate handleClick when count changes  return (
    <div>
      <p>Count: {count}</p>
      <ChildComponent onClick={handleClick} />
    </div>
  );
}function ChildComponent({ onClick }) {
  return (
    <button onClick={onClick}>Increment</button>
  );
}        

In this example, handleClick is memoized using useCallback with the dependency [count]. This ensures that the child component only receives a new function reference when count changes, preventing unnecessary re-renders even if the parent component re-renders due to other state changes.

When Not to Use useCallback:

  • Simple callbacks without dependencies: If a callback function is simple and doesn’t have any dependencies that change frequently, using useCallback might not be necessary. The overhead of memoization could outweigh the potential performance benefit.
  • Callbacks used within the same component: If a callback is only used within the same component where it’s created, there’s no need for useCallback as React already handles component re-renders efficiently.

Example (where useCallback is not needed):

JavaScript

function MyComponent() {
  const handleClick = () => {
    console.log('Clicked!');
  };        
  return (
    <button onClick={handleClick}>Click me</button>
  );
}        

Here, handleClick is a simple function without dependencies and is only used within the same component. Using useCallback wouldn't provide any performance benefit in this case.

Additional Considerations:

  • The dependency array in useCallback is crucial. If you miss out required dependencies, the function might be recreated unexpectedly, leading to unintended behavior.
  • Overusing useCallback can introduce complexity and potentially make your code harder to maintain. Use it judiciously in scenarios where it demonstrably improves performance.

By understanding the use cases and limitations of useCallback, you can effectively leverage it to optimize your React components and enhance their performance.

Bikash Karki

To view or add a comment, sign in

More articles by Kushal Khadka

Others also viewed

Explore content categories