diff --git a/docs/basic/getting-started/hooks.md b/docs/basic/getting-started/hooks.md index f4064dbb..a5fe8dda 100644 --- a/docs/basic/getting-started/hooks.md +++ b/docs/basic/getting-started/hooks.md @@ -215,22 +215,25 @@ function Foo() { ## useImperativeHandle -_We don't have much here, but this is from [a discussion in our issues](https://github.com/typescript-cheatsheets/react/issues/106). Please contribute if you have anything to add!_ - +It's normally used in combination with [`forwardRef`](https://github.com/typescript-cheatsheets/react/blob/main/README.md#forwardrefcreateref), and here's [an example from the React docs](https://reactjs.org/docs/hooks-reference.html#useimperativehandle) typed: + ```tsx -type ListProps = { - items: ItemType[]; - innerRef?: React.Ref<{ scrollToItem(item: ItemType): void }>; -}; - -function List(props: ListProps) { - useImperativeHandle(props.innerRef, () => ({ - scrollToItem() {}, +function FancyInput(props: {}, ref: React.Ref<{ focus: () => void }>) { + const inputRef = useRef(null); + useImperativeHandle(ref, () => ({ + focus: () => { + inputRef.current?.focus(); + }, })); - return null; + return ; } +const Input = forwardRef<{ focus: () => void }, {}>(FancyInput); ``` +### See also + +- [A discussion in our issues](https://github.com/typescript-cheatsheets/react/issues/106) + ## Custom Hooks If you are returning an array in your Custom Hook, you will want to avoid type inference as TypeScript will infer a union type (when you actually want different types in each position of the array). Instead, use [TS 3.4 const assertions](https://devblogs.microsoft.com/typescript/announcing-typescript-3-4/#const-assertions):