From a42c9d84e30cc000bad4df8793eac7d4de66df26 Mon Sep 17 00:00:00 2001 From: Ryan Christian <33403762+rschristian@users.noreply.github.com> Date: Tue, 4 Feb 2025 01:09:18 -0600 Subject: [PATCH] docs: Add info on `useImperativeHandle` (#1228) * docs: Add info on `useImperativeHandle` * docs: Add comment to `useImperativeHandle` example --- content/en/guide/v10/hooks.md | 51 +++++++++++++++++++++++++++++++++-- 1 file changed, 49 insertions(+), 2 deletions(-) diff --git a/content/en/guide/v10/hooks.md b/content/en/guide/v10/hooks.md index c21ecdfae..62c2ca081 100644 --- a/content/en/guide/v10/hooks.md +++ b/content/en/guide/v10/hooks.md @@ -265,7 +265,11 @@ const onClick = useCallback( > Fun fact: `useCallback(fn, deps)` is equivalent to `useMemo(() => fn, deps)`. -## useRef +## Refs + +**Ref**erences are stable, local values that persist across rerenders but don't cause rerenders themselves. See [Refs](/guide/v10/refs) for more information & examples. + +### useRef To create a stable reference to a DOM node or a value that persists between renders, we can use the `useRef` hook. It works similarly to [createRef](/guide/v10/refs#createref). @@ -292,7 +296,50 @@ render(, document.getElementById("app")); > Be careful not to confuse `useRef` with `createRef`. -> See [Refs](/guide/v10/refs) for more information & examples. +### useImperativeHandle + +To mutate a ref that is passed into a child component we can use the `useImperativeHandle` hook. It takes three arguments: the ref to mutate, a function to execute that will return the new ref value, and a dependency array to determine when to rerun. + +```jsx +// --repl +import { render } from "preact"; +import { useRef, useImperativeHandle, useState } from "preact/hooks"; +// --repl-before +function MyInput({ inputRef }) { + const ref = useRef(null); + useImperativeHandle(inputRef, () => { + return { + // Only expose `.focus()`, don't give direct access to the DOM node + focus() { + ref.current.focus(); + }, + }; + }, []); + + return ( + + ); +} + +function App() { + const inputRef = useRef(null); + + const handleClick = () => { + inputRef.current.focus(); + }; + + return ( +
+ + +
+ ); +} +// --repl-after +render(, document.getElementById("app")); +``` ## useContext