|
1 | 1 | import { useMemo } from 'react' |
2 | 2 | import { useSelector, useDispatch } from 'react-redux' |
3 | | -import { bindActionCreators, type Slice } from '@reduxjs/toolkit' |
| 3 | +import { bindActionCreators } from '@reduxjs/toolkit' |
4 | 4 | import { useLatest, bindSelectors } from './utils' |
5 | | -import type { UseSliceReturn } from './useSlice.types' |
| 5 | +import type { Slice, UseSliceReturn } from './useSlice.types' |
6 | 6 |
|
7 | 7 | export function useSlice<T extends Slice>(slice: T): UseSliceReturn<T> { |
8 | | - const state = useSelector(slice.selectSlice) |
| 8 | + const { selectSlice, actions, selectors, name } = slice |
| 9 | + const state = useSelector(selectSlice) |
9 | 10 | const stateRef = useLatest(state) |
10 | 11 | const dispatch = useDispatch() |
11 | 12 |
|
12 | | - const actions = useMemo( |
13 | | - () => bindActionCreators(slice.actions, dispatch), |
14 | | - [slice.actions, dispatch] |
| 13 | + const boundActions = useMemo( |
| 14 | + () => bindActionCreators(actions, dispatch), |
| 15 | + [actions, dispatch] |
15 | 16 | ) |
16 | | - const selectors = useMemo( |
17 | | - () => bindSelectors(slice.selectors, slice.name, stateRef), |
18 | | - [slice.selectors, slice.name, stateRef] |
| 17 | + const boundSelectors = useMemo( |
| 18 | + () => bindSelectors(selectors, name, stateRef), |
| 19 | + [selectors, name, stateRef] |
19 | 20 | ) |
20 | 21 |
|
21 | | - return [state, actions, selectors] |
| 22 | + return [state, boundActions, boundSelectors] |
22 | 23 | } |
0 commit comments