JAVASCRIPT

Optimize Event Handlers with useCallback

Enhance React component performance by using the `useCallback` hook to memoize event handler functions, preventing unnecessary re-renders in child components.

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

const ChildComponent = React.memo(({ onClick, label }) => {
  console.log(`ChildComponent ${label} rendered`);
  return <button onClick={onClick}>{label}</button>;
});

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

  // 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

  // This function will only be re-created if 'text' changes.
  const handleTextChange = useCallback((e) => {
    setText(e.target.value);
  }, []); // Empty dependency array means it's created once

  // If `handleClick` and `handleTextChange` were not wrapped in useCallback,
  // ChildComponent would re-render every time ParentComponent renders (e.g., when 'text' changes and vice versa)
  // because a new function instance would be passed as a prop.

  return (
    <div>
      <p>Count: {count}</p>
      <ChildComponent onClick={handleClick} label='Increment Count' />
      <br />
      <input type='text' value={text} onChange={handleTextChange} placeholder='Type something...' />
      <p>Text: {text}</p>
    </div>
  );
}

export default ParentComponent;
How it works: The `useCallback` hook is crucial for optimizing performance in React applications, especially when passing callback functions to memoized child components. It memoizes the provided function instance, ensuring that the function reference remains the same between re-renders as long as its dependencies haven't changed. This prevents unnecessary re-renders of child components that rely on prop equality checks (e.g., using `React.memo`), as the child won't detect a 'new' function prop on every parent re-render.

Need help integrating this into your project?

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

Hire DigitalCodeLabs