MCPcopy Create free account
hub / github.com/streamich/react-use / createReducer

Function createReducer

src/factory/createReducer.ts:23–65  ·  view source on GitHub ↗
(...middlewares: Middleware<Action, State>[])

Source from the content-addressed store, hash-verified

21}
22
23const 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
67export default createReducer;

Callers 3

setUpFunction · 0.85

Calls 4

composeMiddlewareFunction · 0.85
setStateFunction · 0.85
useUpdateEffectFunction · 0.85
reducerFunction · 0.50

Tested by 1

setUpFunction · 0.68

Used in the wild real call sites across dependent graphs

searching dependent graphs…