useCallback to Memoize Functions

useCallback returns a memoized version of a callback function, which is only redefined when its dependencies change.

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

function Counter() {
  const [count, setCount] = useState(0);

  const increment = useCallback(() => {
    setCount(c => c + 1);
  }, []);

  return <button onClick={increment}>Count: {count}</button>;
}

This helps avoid unnecessary re-renders of child components relying on function props.

← PrevNext →