Last active
February 3, 2022 14:53
-
-
Save mauroc8/599bd2ee6b80501584614590ba8aa6a4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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