Skip to content

Instantly share code, notes, and snippets.

@uhyo
Created January 12, 2022 00:35
Show Gist options
  • Save uhyo/1e0437bc95ec3a501340f98504b38877 to your computer and use it in GitHub Desktop.
Save uhyo/1e0437bc95ec3a501340f98504b38877 to your computer and use it in GitHub Desktop.
useButterflyEffect()
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