← React Beginner Questions - Set 3 Q29

What is the purpose of the useCallback hook?

React Beginner Questions - Set 3

It keeps the same function identity between renders — useful only when that identity is being compared somewhere.

Example

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

const Button = memo(function Button({ onClick, children }) {
  return <button onClick={onClick}>{children}</button>;
});

export default function Counter() {
  const [count, setCount] = useState(0);
  const [other, setOther] = useState(0);

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

  return (
    <>
      <Button onClick={increment}>+1 ({count})</Button>
      <button onClick={() => setOther(o => o + 1)}>unrelated {other}</button>
    </>
  );
}

What to notice

← Back to the question list