Skip to content

Commit 5ec9930

Browse files
committed
Added section on manual typing for useReducer
1 parent fd44701 commit 5ec9930

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,18 @@ export function reducer: Reducer<AppState, Action>() {}
429429

430430
</details>
431431

432+
<details>
433+
434+
<summary><b>Providing explicit types for <code>useReducer</code></b></summary>
435+
436+
In most cases, type inference for useReducer should work reliably. When inference fails, the state and action types can be explicitly provided using the following syntax, where the action type is wrapped in a single-element tuple.
437+
438+
```tsx
439+
const [state, dispatch] = useReducer<typeof initialState, [ACTIONTYPE]>(reducer, initialState);
440+
```
441+
442+
</details>
443+
432444
#### useEffect / useLayoutEffect
433445

434446
Both of `useEffect` and `useLayoutEffect` are used for performing <b>side effects</b> and return an optional cleanup function which means if they don't deal with returning values, no types are necessary. When using `useEffect`, take care not to return anything other than a function or `undefined`, otherwise both TypeScript and React will yell at you. This can be subtle when using arrow functions:

docs/basic/getting-started/hooks.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,18 @@ export function reducer: Reducer<AppState, Action>() {}
138138

139139
</details>
140140

141+
<details>
142+
143+
<summary><b>Providing explicit types for <code>useReducer</code></b></summary>
144+
145+
In most cases, type inference for useReducer should work reliably. When inference fails, the state and action types can be explicitly provided using the following syntax, where the action type is wrapped in a single-element tuple.
146+
147+
```tsx
148+
const [state, dispatch] = useReducer<typeof initialState, [ACTIONTYPE]>(reducer, initialState);
149+
```
150+
151+
</details>
152+
141153
## useEffect / useLayoutEffect
142154

143155
Both of `useEffect` and `useLayoutEffect` are used for performing <b>side effects</b> and return an optional cleanup function which means if they don't deal with returning values, no types are necessary. When using `useEffect`, take care not to return anything other than a function or `undefined`, otherwise both TypeScript and React will yell at you. This can be subtle when using arrow functions:

0 commit comments

Comments
 (0)