← Back to all snippets
JAVASCRIPT

Optimizing Event Handlers with useCallback

Leverage React's `useCallback` hook to memoize function definitions, preventing unnecessary re-renders of child components that depend on stable function references.

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

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

function ParentComponent() {
  const [count, setCount] = useState(0);
  const [text, setText] = useState('');

  // Without useCallback, handleIncrement would be a new function on every render,
  // causing Button to re-render even if its own state/props haven't logically changed.
  const handleIncrement = useCallback(() => {
    setCount(prevCount => prevCount + 1);
  }, []); // Empty dependency array means this function reference will never change

  const handleTextChange = useCallback((event) => {
    setText(event.target.value);
  }, []); // Empty dependency array means this function reference will never change

  return (
    <div>
      <h1>Count: {count}</h1>
      <Button onClick={handleIncrement}>Increment</Button>

      <h2>Text Input</h2>
      <input type="text" value={text} onChange={handleTextChange} placeholder="Type something..." />
      <p>Current text: {text}</p>

      <p>ParentComponent renders: {Math.random().toFixed(2)}</p>
    </div>
  );
}

export default ParentComponent;
How it works: This example uses `useCallback` to memoize event handler functions (`handleIncrement`, `handleTextChange`). Without `useCallback`, these functions would be re-created on every render of `ParentComponent`, leading to `Button` re-rendering unnecessarily (because its `onClick` prop would be a new function reference each time), even though `Button` is wrapped in `React.memo`. By wrapping them in `useCallback` with an empty dependency array, we ensure their references remain stable across renders, allowing `React.memo` to effectively prevent re-renders of the `Button` component unless its other props truly change.

Need help integrating this into your project?

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

Hire DigitalCodeLabs