Skip to content

Instantly share code, notes, and snippets.

@titoasty
Last active July 6, 2020 08:00
Show Gist options
  • Save titoasty/49c4cb0d88abc396a757941c685727de to your computer and use it in GitHub Desktop.
Save titoasty/49c4cb0d88abc396a757941c685727de to your computer and use it in GitHub Desktop.
create a simple shared hook between components
import { useReducer, useEffect } from 'react';
const useForceUpdate = () => useReducer((state) => !state, false)[1];
function createSharedState(reducer, initialState) {
const subscribers: any[] = [];
let state = initialState;
const dispatch = (action) => {
state = reducer(state, action);
subscribers.forEach((callback) => callback());
};
const useSharedState = () => {
const forceUpdate = useForceUpdate();
useEffect(() => {
const callback = () => forceUpdate();
subscribers.push(callback);
callback(); // in case it's already updated
const cleanup = () => {
const index = subscribers.indexOf(callback);
subscribers.splice(index, 1);
};
return cleanup;
}, []);
return [state, dispatch];
};
return useSharedState;
}
export default function createSharedHook(initialState) {
const reducer = (state, action) => action;
const hook = createSharedState(reducer, initialState);
return hook;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment