I store config settings, set by the client, in local storage. When somebody updates a value, we save it to local storage. When they load the page, we grab it from local storage. The code for a sticky state is:
import React from 'react';
export default function useStickyState(key, defaultValue) {
if (!process.browser) {
return React.useState({})
}
const [value, setValue] = React.useState(() => {
const stickyValue = window.localStorage.getItem(key);
return stickyValue !== null
? JSON.parse(stickyValue)
: defaultValue;
});
React.useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
Using this, I can make a settings system pretty easily:
import useStickyState from "./useStickyState";
export default function useSettings() {
const [config, setConfig] = useStickyState('config', {
shortLength: 4,
password: '',
expirationTime: 0,
focus: 'usability'
})
return [config, setConfig]
}
Then, I can access settings using:
const [config, setConfig] = useSettings()
However. I have multiple components that use these settings. When one of them calls setConfig(), I want them all to update. Is this possible? How would one go about doing this?
The only method I can think of at the moment is polling every x seconds, which seems an awful solution.