bhylu.com

Advertisements

React useRef

Use a ref for a DOM node or retained value that does not itself determine the visible view.

How it works

useRef returns a stable object whose current field can be assigned without requesting a render. That makes it suitable for a DOM node or an external timer handle. It is not a substitute for state when a value should change the screen. This example lets a button focus an existing input. React fills the ref after committing the input, so the handler checks that the node exists before using it.

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

function App() {
  const input = useRef(null);
  return (
    <main>
      <h1>Neighbourhood lending desk</h1>
      <label>
        Item search
        <input ref={input} />
      </label>
      <button onClick={() => input.current?.focus()}>Focus item search</button>
    </main>
  );
}

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

Expected result

Clicking the button places keyboard focus in the labelled search field.

The ref is read from an event handler, where interacting with the DOM is appropriate. The browser focus operation does not need a second React state value. Avoid reading or writing arbitrary ref values during rendering to coordinate hidden state; that can break the snapshot model. State should still represent data that users see, such as the search query or selected record.

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

Advertisements