Package Exports
- @plq/use-persisted-state
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@plq/use-persisted-state) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
usePersistedState
Persists the state to localStorage, sessionStorage or anything else that implements getItem
, setItem
and removeItem
Features
- Persist the state to
localStorage
,sessionStorage
or anything else that implementsgetItem
,setItem
andremoveItem
- State changes are syncing between tabs or windows
- The state factory takes as many keys as needed, so you don't have to call the factory for each variable
- Written with the Typescript, the defenitions go with the library
- No dependencies
- Only 645B (minified and gziped)
Example
import createPersistedState from '@plq/use-persisted-state'
const [usePersistedState] = createPersistedState('example')
export default function App() {
const [count, setCount] = usePersistedState('count', 0)
const handleIncrement = () => setCount(prevCount => prevCount + 1)
return (
<div>
{count}
<button onClick={handleIncrement}>+</button>
</div>
)
}
Little bit closer to real life:
Requirement
To use @plq/use-persisted-state
, you must use react@16.8.0
or greater which includes Hooks.
Clear Storage
import createPersistedState from '@plq/use-persisted-state'
const [usePersistedState, clear] = createPersistedState('example')
export default function App() {
const [count, setCount] = usePersistedState('count', 0)
const increment = () => setCount(prevCount => prevCount + 1)
return (
<div>
{count}
<button onClick={increment}>+</button>
<button onClick={clear}>Clear</button>
</div>
)
}
Use sessionStorage
import createPersistedState from '@plq/use-persisted-state'
const [usePersistedState] = createPersistedState('example', window.sessionStorage)
export default function App() {
const [count, setCount] = usePersistedState('count', 0)
const increment = () => setCount(prevCount => prevCount + 1)
return (
<div>
{count}
<button onClick={increment}>+</button>
</div>
)
}
Use custom storage
import createPersistedState from '@plq/use-persisted-state'
const myStorage = {
getItem: (key) => getItemFromSomeStorage(key)
setItem: (key, value) => setItemToSomeStorage(key, value)
removeItem: (key) => removeItemFromSomeStorage(key)
}
const [usePersistedState] = createPersistedState('example', myStorage)
export default function App() {
const [count, setCount] = usePersistedState('count', 0)
const increment = () => setCount(prevCount => prevCount + 1)
return (
<div>
{count}
<button onClick={increment}>+</button>
</div>
)
}
ToDo
- Support async storage