Skip to content

Instantly share code, notes, and snippets.

@caasi
Created September 22, 2021 21:49
Show Gist options
  • Save caasi/6c88bbfb76cce656727b612703ac62cb to your computer and use it in GitHub Desktop.
Save caasi/6c88bbfb76cce656727b612703ac62cb to your computer and use it in GitHub Desktop.
type SetStateAction<S> = S | (prevState: S) => S;
export const isStateTransition = <S>(
x: SetStateAction<S>
): x is StateTransition<S> => {
return typeof x === "function";
};
export const tapStateAction = <S>(
s: SetStateAction<S>,
f: (x: S) => void
): SetStateAction<S> => {
if (isStateTransition(s)) {
return (prevState: S) => {
const newState = s(prevState);
f(newState);
return newState;
};
}
f(s);
return s;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment