useStoredState
useStoredState is a custom react hook that can persist using either localStorage, sessionStorage, or an object that follows the same rules.
Example Usage
In the following code, both components will stay in sync with each other, and if you open up two browser windows (they have to share localStorage so keep them the same, eg chrome/chrome). If you do a page refresh it will load the previous state and persists.
If you create an object that has setItem/getItem/removeItem function propertys that follow the same rules as localStorage, you can create your own adapter essentially to save state to a server or whatever else you want to do.
import './App.css';
import { useStoredState } from './useStoredState';
const Name = ({nameId}) => {
const [name, setName] = useStoredState(localStorage, 'stored', nameId, 'Dan Teel');
return <input type='text' value={name ? name.name : ''} onChange={(e)=>setName({name: e.target.value})}/>
}
function App() {
return (
<div className='App'>
<Name nameId='name'/>
<Name nameId='name'/>
</div>
);
}
export default App;