Skip to content

Commit 7d84c99

Browse files
committed
custom hooks advice
1 parent 382c395 commit 7d84c99

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

README.md

+27-2
Original file line numberDiff line numberDiff line change
@@ -435,13 +435,38 @@ export interface Props {
435435

436436
Hooks are supported in `@types/react` from v16.7 up.
437437

438-
Many hooks are initialized with null-ish default values, and you may wonder how to provide types. Do this:
438+
**useState**
439+
440+
Many hooks are initialized with null-ish default values, and you may wonder how to provide types. Use union types:
439441

440442
```tsx
441443
const [user, setUser] = useState<IUser | null>(null);
444+
445+
// later...
446+
setUser(newUser)
447+
```
448+
449+
**Custom Hooks**
450+
451+
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, assert or define the function return types:
452+
453+
```tsx
454+
export function useLoading() {
455+
const [isLoading, setState] = React.useState(false);
456+
const load = (aPromise: Promise<any>) => {
457+
setState(true);
458+
return aPromise.finally(() => {
459+
setState(false);
460+
});
461+
};
462+
return [isLoading, load] as [
463+
boolean,
464+
(aPromise: Promise<any>) => Promise<any>
465+
];
466+
}
442467
```
443468

444-
If you are writing a React Hooks library, don't forget that you can also expose
469+
If you are writing a React Hooks library, don't forget that you can also expose your types.
445470

446471
[Something to add? File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new).
447472

0 commit comments

Comments
 (0)