JAVASCRIPT

Optimize Event Handlers with useCallback for Performance

Discover how to use React's `useCallback` hook to memoize functions, preventing unnecessary re-renders of child components when passing callbacks as props.

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

// A child component that might re-render unnecessarily if its props change often
const Button = React.memo(({ onClick, children }) => {
  console.log('Button rendered');
  return <button onClick={onClick}>{children}</button>;
});

function ParentComponent() {
  const [count, setCount] = useState(0);
  const [otherState, setOtherState] = useState(0);

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

  // Without useCallback, a new handleClick function would be created on every render
  // causing Button to re-render even if its children don't change.

  return (
    <div>
      <p>Count: {count}</p>
      <p>Other State: {otherState}</p>
      <Button onClick={handleClick}>Increment Count</Button>
      <button onClick={() => setOtherState(prev => prev + 1)}>Change Other State</button>
    </div>
  );
}

export default ParentComponent;
How it works: `useCallback` returns a memoized version of the callback function that only changes if one of the dependencies has changed. In this example, `handleClick` is memoized with an empty dependency array `[]`, meaning it will only be created once. When `ParentComponent` re-renders due to `otherState` changing, the `handleClick` function reference remains the same, preventing the `Button` child component (which is wrapped in `React.memo`) from re-rendering unnecessarily.

Need help integrating this into your project?

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

Hire DigitalCodeLabs