bhylu.com

Advertisements

React useImperativeHandle

Use useImperativeHandle when a component should offer a small method instead of its full DOM node.

How it works

A public ref can accidentally couple a parent to a child’s markup. useImperativeHandle lets the child expose a deliberate handle, such as focusSearch, while retaining the input node privately. This is useful for library components and specific focus workflows. It is unnecessary for ordinary value updates, which should remain declarative. The example keeps a private DOM ref and exposes one method with a stable dependency list.

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, useRef, useImperativeHandle } from 'react';
import { createRoot } from 'react-dom/client';
import './style.css';

function Search({ ref }) {
  const node = useRef(null);
  useImperativeHandle(
    ref,
    () => ({
      focusSearch() {
        node.current?.focus();
      },
    }),
    [],
  );
  return (
    <label>
      Search items
      <input ref={node} />
    </label>
  );
}
function App() {
  const search = useRef(null);
  return (
    <main>
      <h1>Neighbourhood lending desk</h1>
      <Search ref={search} />
      <button onClick={() => search.current?.focusSearch()}>
        Focus through the handle
      </button>
    </main>
  );
}

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

Expected result

The parent focuses the search field by calling the named handle method.

The handle does not reveal value, style or the rest of the DOM API. Its method reads node.current at call time, so it does not retain an obsolete input reference. If a handle method closes over reactive props, include those dependencies or redesign the contract. Keep such APIs small enough that a parent cannot silently bypass state invariants.

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

Advertisements