JAVASCRIPT

Optimizing Performance with `useCallback`

Learn to prevent unnecessary re-renders in child components by memoizing callback functions using React's `useCallback` hook, improving application performance.

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

// A child component that re-renders if its props change
const ChildComponent = React.memo(({ onClick, value }) => {
  console.log('ChildComponent re-rendered');
  return (
    <div>
      <p>Child Value: {value}</p>
      <button onClick={onClick}>Click Child</button>
    </div>
  );
});

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

  // Without useCallback, handleClick would be re-created on every ParentComponent render,
  // causing ChildComponent to re-render even if 'text' changes.
  const handleClick = useCallback(() => {
    setCount(prevCount => prevCount + 1);
    console.log('Child button clicked. Count:', count);
  }, [count]); // Dependency array ensures handleClick only changes when count changes.

  return (
    <div>
      <h1>Parent Count: {count}</h1>
      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="Type something..."
      />
      <ChildComponent onClick={handleClick} value={count} />
      <p>Parent Text: {text}</p>
    </div>
  );
}

export default ParentComponent;
How it works: The `useCallback` hook is used to memoize functions, preventing them from being re-created on every render if their dependencies haven't changed. This is particularly useful when passing callback props to optimized child components (like those wrapped with `React.memo`), as it prevents the child from re-rendering unnecessarily due to a new function reference, even if the function's logic is effectively the same. It takes a function and a dependency array, returning a memoized version of the function.

Need help integrating this into your project?

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

Hire DigitalCodeLabs