This is not library/dependency. It's a simple pattern you copy and go.
- You Might Not Need an Effect.
- Libraries like useEffectReducer refer to
useEffect
. - Performing effects from events while updating state is actually very simple:
type UseEffectReducer<S, A> = [
state: S,
dispatch: (action: A) => void,
];
export function useEffectReducer<S, A>(reducer: (state: S, action: A) => S, initialState: S): UseEffectReducer<S, A> {
const [state, setState] = useState<S>(initialState);
const dispatch = (action: A) => {
setState(reducer(state, action));
};
return [state, dispatch];
}
function myReducer(...) {
// perform effects as needed
}
Of course, can have different signatures of reducer:
function myReducer(state: S, action: A, doSomething: () => void): S {
//...
doSomething();
//...
}
dispatch
should be called from events, not effects.- Errors properly handled so they don't fail the reducer.
By Cause Chung (cuzfrog@gmail.com).
CC0 1.0. To view a copy of this license, visit https://creativecommons.org/publicdomain/zero/1.0/