Skip to content

Instantly share code, notes, and snippets.

@nico-martin
Last active November 22, 2021 13:34
Show Gist options
  • Select an option

  • Save nico-martin/4bd4bcbac096f250a07c230ec7a25a18 to your computer and use it in GitHub Desktop.

Select an option

Save nico-martin/4bd4bcbac096f250a07c230ec7a25a18 to your computer and use it in GitHub Desktop.
A React Context Provider to share State between reloads or even between tabs,
import React from 'react';
interface StateI {
[key: string]: any;
}
const Context = React.createContext<{
state: StateI;
setState: (state: StateI) => void;
}>({
state: {},
setState: () => {},
});
export const LocalStorageProvider = ({
children,
storeKey = 'test',
useSessionStorage = false,
}: {
children: any;
storeKey?: string;
useSessionStorage?: boolean;
}) => {
const [store, setStore] = React.useState<StateI>({});
const storage = useSessionStorage ? sessionStorage : localStorage;
React.useEffect(() => {
setStore(getStore());
window.addEventListener('storage', (event) => {
if (event.key === storeKey) {
setStore(getStore());
}
});
}, []);
const getStore = (): StateI =>
JSON.parse(storage.getItem(storeKey)) as StateI;
const updateStore = (part: StateI) => {
const store = getStore();
const newStore = { ...store, ...part };
storage.setItem(storeKey, JSON.stringify(newStore));
setStore(newStore);
};
return (
<Context.Provider value={{ state: store, setState: updateStore }}>
{children}
</Context.Provider>
);
};
export const useLocalStorage = (): [StateI, (state: StateI) => void] => {
const { state, setState } = React.useContext(Context);
return [state, setState];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment