Last active
January 15, 2021 19:55
-
-
Save fauxsaurus/fe9dc4c505b32f0ffe2e1a7867cf52f5 to your computer and use it in GitHub Desktop.
This file contains 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
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