Skip to content

Instantly share code, notes, and snippets.

@pSapien
Created September 14, 2020 13:30
Show Gist options
  • Save pSapien/254b5fdd5efbec0e0192199db8f82593 to your computer and use it in GitHub Desktop.
Save pSapien/254b5fdd5efbec0e0192199db8f82593 to your computer and use it in GitHub Desktop.
Event driven approach in react
/**
*. useEvent hook
*
* @example
const { dispatch, on, events } = useEvents();
useEffect(() => on('MyEvent', (data) => { ...do something...}));
*/
const events = [];
const callbacks = {};
function useForceUpdate() {
const [, setState] = useState(null);
return useCallback(() => setState({}), []);
}
function useEvents() {
const forceUpdate = useForceUpdate();
const runCallbacks = (callbackList, data) => {
if (callbackList) {
callbackList.forEach(cb => cb(data));
forceUpdate();
}
}
const dispatch = (event, data) => {
events.push({ event, data, created: Date.now() });
runCallbacks(callbacks[event], data);
}
const on = (event, cb) => {
if (callbacks[event]) {
callbacks[event].push(cb);
} else {
callbacks[event] = [cb];
}
// Return a cleanup function to unbind event
return () => callbacks[event] = callbacks[event].filter(i => i !== cb);
}
return { dispatch, on, events };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment