Skip to content

Commit a42c9d8

Browse files
authored
docs: Add info on useImperativeHandle (#1228)
* docs: Add info on `useImperativeHandle` * docs: Add comment to `useImperativeHandle` example
1 parent 29f6b9b commit a42c9d8

File tree

1 file changed

+49
-2
lines changed

1 file changed

+49
-2
lines changed

content/en/guide/v10/hooks.md

+49-2
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,11 @@ const onClick = useCallback(
265265
266266
> Fun fact: `useCallback(fn, deps)` is equivalent to `useMemo(() => fn, deps)`.
267267
268-
## useRef
268+
## Refs
269+
270+
**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.
271+
272+
### useRef
269273
270274
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).
271275
@@ -292,7 +296,50 @@ render(<Foo />, document.getElementById("app"));
292296
293297
> Be careful not to confuse `useRef` with `createRef`.
294298
295-
> See [Refs](/guide/v10/refs) for more information & examples.
299+
### useImperativeHandle
300+
301+
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.
302+
303+
```jsx
304+
// --repl
305+
import { render } from "preact";
306+
import { useRef, useImperativeHandle, useState } from "preact/hooks";
307+
// --repl-before
308+
function MyInput({ inputRef }) {
309+
const ref = useRef(null);
310+
useImperativeHandle(inputRef, () => {
311+
return {
312+
// Only expose `.focus()`, don't give direct access to the DOM node
313+
focus() {
314+
ref.current.focus();
315+
},
316+
};
317+
}, []);
318+
319+
return (
320+
<label>
321+
Name: <input ref={ref} />
322+
</label>
323+
);
324+
}
325+
326+
function App() {
327+
const inputRef = useRef(null);
328+
329+
const handleClick = () => {
330+
inputRef.current.focus();
331+
};
332+
333+
return (
334+
<div>
335+
<MyInput inputRef={inputRef} />
336+
<button onClick={handleClick}>Click To Edit</button>
337+
</div>
338+
);
339+
}
340+
// --repl-after
341+
render(<App />, document.getElementById("app"));
342+
```
296343
297344
## useContext
298345

0 commit comments

Comments
 (0)