Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve section useImperativeHandle #446

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 14 additions & 11 deletions docs/basic/getting-started/hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<ItemType> = {
items: ItemType[];
innerRef?: React.Ref<{ scrollToItem(item: ItemType): void }>;
};

function List<ItemType>(props: ListProps<ItemType>) {
useImperativeHandle(props.innerRef, () => ({
scrollToItem() {},
function FancyInput(props: {}, ref: React.Ref<{ focus: () => void }>) {
const inputRef = useRef<HTMLInputElement>(null);
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current?.focus();
},
}));
return null;
return <input ref={inputRef} />;
}
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):
Expand Down