← Back to all snippets
JAVASCRIPT

Optimizing Callbacks with React's useCallback Hook

Discover how `useCallback` in React helps optimize performance by memoizing event handler functions, preventing unnecessary re-renders of child components in your applications.

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

const ChildComponent = React.memo(({ onClick }) => {
  console.log('ChildComponent rendered');
  return <button onClick={onClick}>Click Child</button>;
});

function ParentComponent() {
  const [count, setCount] = useState(0);
  const [anotherState, setAnotherState] = useState(0);

  const handleClick = useCallback(() => {
    setCount(prevCount => prevCount + 1);
    console.log('Parent button clicked');
  }, []);

  const handleAnotherClick = useCallback(() => {
    setAnotherState(prev => prev + 1);
  }, []);

  return (
    <div>
      <h1>Parent Count: {count}</h1>
      <button onClick={handleAnotherClick}>Increment Another State ({anotherState})</button>
      <p>This button increments parent's 'anotherState', but ChildComponent will not re-render.</p>
      <ChildComponent onClick={handleClick} />
    </div>
  );
}

export default ParentComponent;
How it works: The `useCallback` hook is used to memoize functions. When a component re-renders, JavaScript functions declared within it are re-created. If these functions are passed as props to child components (especially `React.memo`ized ones), the child components might unnecessarily re-render because their prop (the function) appears to have changed. `useCallback` returns a memoized version of the callback function that only changes if one of its dependencies has changed, thus preventing unnecessary re-renders of dependent child components and improving performance.

Need help integrating this into your project?

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

Hire DigitalCodeLabs