diff --git a/README.md b/README.md index 6bcfdcc4..0a828cca 100644 --- a/README.md +++ b/README.md @@ -384,7 +384,10 @@ type ACTIONTYPE = | { type: "increment"; payload: number } | { type: "decrement"; payload: string }; -function reducer(state: typeof initialState, action: ACTIONTYPE) { +function reducer( + state: typeof initialState, + action: ACTIONTYPE +): typeof initialState { switch (action.type) { case "increment": return { count: state.count + action.payload }; @@ -429,6 +432,21 @@ export function reducer: Reducer() {} +
+ +Providing explicit types for useReducer + +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. + +```tsx +const [state, dispatch] = useReducer( + reducer, + initialState +); +``` + +
+ #### useEffect / useLayoutEffect Both of `useEffect` and `useLayoutEffect` are used for performing side effects 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: diff --git a/docs/basic/getting-started/hooks.md b/docs/basic/getting-started/hooks.md index 19fb03f4..bd3254df 100644 --- a/docs/basic/getting-started/hooks.md +++ b/docs/basic/getting-started/hooks.md @@ -93,7 +93,10 @@ type ACTIONTYPE = | { type: "increment"; payload: number } | { type: "decrement"; payload: string }; -function reducer(state: typeof initialState, action: ACTIONTYPE) { +function reducer( + state: typeof initialState, + action: ACTIONTYPE +): typeof initialState { switch (action.type) { case "increment": return { count: state.count + action.payload }; @@ -138,6 +141,21 @@ export function reducer: Reducer() {} +
+ +Providing explicit types for useReducer + +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. + +```tsx +const [state, dispatch] = useReducer( + reducer, + initialState +); +``` + +
+ ## useEffect / useLayoutEffect Both of `useEffect` and `useLayoutEffect` are used for performing side effects 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: