(...middlewares: Middleware<Action, State>[])
| 21 | } |
| 22 | |
| 23 | const createReducer = <Action, State>(...middlewares: Middleware<Action, State>[]) => { |
| 24 | const composedMiddleware = composeMiddleware<Action, State>(middlewares); |
| 25 | |
| 26 | return ( |
| 27 | reducer: (state: State, action: Action) => State, |
| 28 | initialState: State, |
| 29 | initializer = (value: State) => value |
| 30 | ): [State, Dispatch<Action>] => { |
| 31 | const ref = useRef(initializer(initialState)); |
| 32 | const [, setState] = useState(ref.current); |
| 33 | |
| 34 | const dispatch = useCallback( |
| 35 | (action) => { |
| 36 | ref.current = reducer(ref.current, action); |
| 37 | setState(ref.current); |
| 38 | return action; |
| 39 | }, |
| 40 | [reducer] |
| 41 | ); |
| 42 | |
| 43 | const dispatchRef: MutableRefObject<Dispatch<Action>> = useRef( |
| 44 | composedMiddleware( |
| 45 | { |
| 46 | getState: () => ref.current, |
| 47 | dispatch: (...args: [Action]) => dispatchRef.current(...args), |
| 48 | }, |
| 49 | dispatch |
| 50 | ) |
| 51 | ); |
| 52 | |
| 53 | useUpdateEffect(() => { |
| 54 | dispatchRef.current = composedMiddleware( |
| 55 | { |
| 56 | getState: () => ref.current, |
| 57 | dispatch: (...args: [Action]) => dispatchRef.current(...args), |
| 58 | }, |
| 59 | dispatch |
| 60 | ); |
| 61 | }, [dispatch]); |
| 62 | |
| 63 | return [ref.current, dispatchRef.current]; |
| 64 | }; |
| 65 | }; |
| 66 | |
| 67 | export default createReducer; |
searching dependent graphs…