Created
January 12, 2022 00:35
-
-
Save uhyo/1e0437bc95ec3a501340f98504b38877 to your computer and use it in GitHub Desktop.
useButterflyEffect()
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
const effects: Map<number, () => void> = new Map(); | |
let nextEffectId = 1; | |
/** | |
* Similar to useEffect, but an effect from another randomly chosen instance of useButterflyEffect is called | |
* when given deps change. | |
*/ | |
function useButterflyEffect(effect: () => void, deps: readonly unknown[]) { | |
useEffect(() => { | |
const effectId = nextEffectId++; | |
effects.set(effectId, effect); | |
const currentEffects = [...effects.values()]; | |
const randomEffect = currentEffects[Math.floor(Math.random() * currentEffects.length)]; | |
randomEffect(); | |
return () => { | |
effects.delete(effectId); | |
} | |
}, deps) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment