JAVASCRIPT

Optimizing Performance with useCallback Hook

Improve React component performance by memoizing functions with the `useCallback` hook, preventing unnecessary re-renders of child components.

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

function Button({ onClick, children }) {
  console.log(`Button ${children} rendered`);
  return <button onClick={onClick}>{children}</button>;
}

const MemoizedButton = React.memo(Button);

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

  // This function is recreated on every render without useCallback
  // const handleClick = () => {
  //   setCount(prevCount => prevCount + 1);
  // };

  // Memoized version of handleClick
  const handleClick = useCallback(() => {
    setCount(prevCount => prevCount + 1);
  }, []); // Empty dependency array means it's created once

  const handleInputChange = (e) => {
    setText(e.target.value);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <input type="text" value={text} onChange={handleInputChange} placeholder="Type something..." />
      <MemoizedButton onClick={handleClick}>Increment Count</MemoizedButton>
      <p>Input Text: {text}</p>
    </div>
  );
}

export default ParentComponent;
How it works: The `useCallback` hook memoizes a function, returning a memoized version of the callback that only changes if one of the dependencies has changed. This is particularly useful when passing callbacks to optimized child components that rely on reference equality (e.g., components wrapped with `React.memo`), preventing them from re-rendering unnecessarily when the parent component re-renders.

Need help integrating this into your project?

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

Hire DigitalCodeLabs