bhylu.com

Advertisements

React useCallback

Use useCallback when function identity matters to a consumer, and include every reactive dependency.

How it works

useCallback caches a function identity between renders until its dependencies change. It does not make the function’s body faster. It is useful when a memoized child receives a callback that would otherwise change on every parent render. The example separates an unrelated review count from a child action. The callback uses a functional state updater, so it does not need to capture the current acknowledgement count.

Run the code

Use a separate empty lab folder with Node 22.12+ in the 22 series. Save the files below using their displayed paths; browsers may download only the basename, so create src, public or tests folders as listed. The pinned project uses React and React DOM 19.3.1 with Vite 7.3.1. Run npm install, then npm run dev and open the local address Vite prints. React examples do not run in Bhylu’s current playground.

No Apache, MySQL or change to Bhylu’s server configuration is needed. These are local teaching projects, not a publishing package. Keep generated dependencies and lockfiles in your own lab. Review the project setup.

Example

src/main.jsx

import React, { StrictMode, useState, useEffect, useCallback, memo } from 'react';
import { createRoot } from 'react-dom/client';
import './style.css';

export let actionRenders = 0;
const Action = memo(function Action({ onRead }) {
  useEffect(() => {
    actionRenders++;
  });
  return <button onClick={onRead}>Read item notice</button>;
});
function App() {
  const [reviews, setReviews] = useState(0);
  const [reads, setReads] = useState(0);
  const onRead = useCallback(() => setReads((value) => value + 1), []);
  return (
    <main>
      <h1>Neighbourhood lending desk</h1>
      <button onClick={() => setReviews((value) => value + 1)}>Unrelated review</button>
      <Action onRead={onRead} />
      <output>
        Reviews {reviews}; reads {reads}
      </output>
    </main>
  );
}

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>,
);

Expected result

The unrelated count and read count both work, while the memoized action can reuse its stable callback prop.

The callback has an empty dependency list because it only uses a stable setter and an updater argument. If it later reads a prop, that prop must be included. An ordinary inline function is simpler when identity is irrelevant. Keep this optimization tied to measured work instead of sprinkling hooks across every button.

For API contracts and version differences, use React’s official documentation.

Advertisements