From 44f2a00159b064bebadb978d57467da4f352f8be Mon Sep 17 00:00:00 2001 From: pawannyadav05 Date: Sat, 21 Nov 2026 00:25:05 +0530 Subject: [PATCH] docs: add callback ref example for focusing input on mount Adds a new recipe to the useRef reference page demonstrating how to focus an input element on mount using a callback ref (function ref) rather than a useRef object ref. This addresses the documented use case in issue #8718 where users want to focus an element automatically without needing a button click, and where useCallback ensures the ref callback is stable across renders. Closes #8718 --- src/content/reference/react/useRef.md | 32 +++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/content/reference/react/useRef.md b/src/content/reference/react/useRef.md index 6f7728f0a2a..e4ee98f368d 100644 --- a/src/content/reference/react/useRef.md +++ b/src/content/reference/react/useRef.md @@ -300,6 +300,38 @@ export default function Form() { +#### Focusing an input using a callback ref {/*focusing-an-input-using-a-callback-ref*/} + +Instead of a ref object, you can pass a **callback function** to the `ref` attribute. React will call your callback with the DOM node when it mounts, and with `null` when it unmounts. This is useful when you need to focus the element immediately on mount without a button click. + + + +```js +import { useCallback } from 'react'; + +export default function Form() { + const inputRef = useCallback((node) => { + if (node !== null) { + node.focus(); + } + }, []); + + return ( + <> + +

The input above is focused automatically on mount.

+ + ); +} +``` + +
+ + + #### Scrolling an image into view {/*scrolling-an-image-into-view*/} In this example, clicking the button will scroll an image into view. It uses a ref to the list DOM node, and then calls DOM [`querySelectorAll`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) API to find the image we want to scroll to.