JAVASCRIPT

Prevent Unnecessary Re-renders with useCallback

Discover how React's useCallback hook helps optimize child component rendering by providing a memoized version of callback functions, crucial for React.memo.

import React, { useState, useCallback, memo } from 'react';

const Button = memo(({ onClick, children }) => {
  console.log('Button rendered');
  return <button onClick={onClick}>{children}</button>;
});

function ParentComponent() {
  const [count, setCount] = useState(0);
  const [toggle, setToggle] = useState(false);

  // This function will only be re-created if 'count' changes
  const handleClick = useCallback(() => {
    setCount(prevCount => prevCount + 1);
  }, []); // Empty dependency array means it's created once

  const handleToggle = () => {
    setToggle(prevToggle => !prevToggle);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <p>Toggle: {toggle ? 'On' : 'Off'}</p>
      <Button onClick={handleClick}>Increment Count</Button>
      <button onClick={handleToggle}>Toggle State</button>
    </div>
  );
}
How it works: The `useCallback` hook memoizes a function definition itself. When `ParentComponent` re-renders due to `toggle` state change, `handleClick` remains the same reference because its dependencies `[]` haven't changed. This prevents the `Button` component (which is wrapped in `memo`) from re-rendering unnecessarily, as its `onClick` prop reference hasn't changed, optimizing rendering performance.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs