Skip to content

Instantly share code, notes, and snippets.

@mauroc8
Last active February 3, 2022 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mauroc8/599bd2ee6b80501584614590ba8aa6a4 to your computer and use it in GitHub Desktop.
Save mauroc8/599bd2ee6b80501584614590ba8aa6a4 to your computer and use it in GitHub Desktop.
type Dispatch<Action> = (action: Action) => void;
export function useReducerWithManagedEffects<State, Action, Effect>(
reducer: (state: State, action: Action) => [ State, Effect ],
runEffect: (effect: Effect, dispatch: Dispatch<Action>) => void,
initialState: State
): [ State, Dispatch<Action> ] {
const [ state, setState ] = useState(initialState);
const dispatch: Dispatch<Action> = useCallback(
(action: Action) => {
setState(state => {
const [ newState, effect ] = reducer(state, action);
runEffect(effect, dispatch);
return newState;
});
},
[ reducer, runEffect ]
);
return [ state, dispatch ];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment