Skip to content

Instantly share code, notes, and snippets.

@benhorst
Last active May 24, 2020 02:15
Show Gist options
  • Save benhorst/fbe2656cce8cddead6f729f9915a6326 to your computer and use it in GitHub Desktop.
Save benhorst/fbe2656cce8cddead6f729f9915a6326 to your computer and use it in GitHub Desktop.
Simple KeyStore React Context (and provider)
import { createContext, useReducer } from 'react';
const reducer = (initialValue) => (state, { type, key, value }) => {
switch (type) {
case 'SET_KEY':
return { ...state, [key]: value };
case 'CLEAR':
return initialValue;
default:
return state;
}
};
export const CreateKeyStoreContext = (name, defaultValue) => {
const KeyStoreContext = createContext(defaultValue);
const Provider = ({ children }) => {
const [state, dispatch] = useReducer(reducer(defaultValue), defaultValue);
const setKey = (key, value) => dispatch({ type: 'SET_KEY', key, value });
const clear = () => dispatch({ type: 'CLEAR' });
return <KeyStoreContext.Provider value={ { state, setKey, clear } }>{ children }</KeyStoreContext.Provider>;
};
return {
['use'+name+'Context']: () => useContext(KeyStoreContext),
[name+'Provider']: Provider,
};
}
// USAGE: write a BlechContext.js file and put this in it!
export const { BlechProvider, useBlechContext } = CreateKeyStoreContext('Blech', { blork: true, black: 'white' });
// Maybe you want a Settings or Preferences set of Map<string, value>
export const { SettingsProvider, useSettingsContext } = CreateKeyStoreContext('Settings', { hints: true, highContrast: false });
//Then in your app:
import { SettingsProvider } from '/contexts/SettingsContext';
React.render(
document.getElementById('app'),
<SettingsProvider><App /></SettingsProvider>
);
// and in some other file, a way to disable all tooltips when "hints" are off
import { useSettingsContext } from '/contexts/SettingsContext';
const HintTooltip = ({ text }) => {
const { state: settings, setKey } = useSettingsContext();
return settings.hints && (
<Tooltip name="hint">text</Tooltip>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment