Skip to content

Instantly share code, notes, and snippets.

@fauxsaurus
Last active January 15, 2021 19:55
Show Gist options
  • Save fauxsaurus/fe9dc4c505b32f0ffe2e1a7867cf52f5 to your computer and use it in GitHub Desktop.
Save fauxsaurus/fe9dc4c505b32f0ffe2e1a7867cf52f5 to your computer and use it in GitHub Desktop.
export const useStateChangeEffect = <S>(
initialState: S,
effect: (arg: S) => void,
runIf: (arg: S) => boolean = isTrue => !!isTrue,
) => {
const [state, setState] = useState(initialState);
const prevState = useRef(state);
const triggerEffect = runIf(state) && state !== prevState.current;
useEffect(() => void (triggerEffect && effect(state)), [effect, state, triggerEffect]);
useEffect(() => void (prevState.current = state)); // note: must come after
return [state, setState] as const;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment