use-local-storage
Usage
use-local-storage allows you to use value from localStorage as react state.
Hook works the same way as useState, but also writes the value to localStorage:
Example
Mantine docs website uses this hook to store color scheme information:
Remove value
Use removeValue callback to clean localStorage/sessionStorage.
When value is removed it is reset to defaultValue:
Browser tabs synchronization
use-local-storage subscribes to storage event.
When state changes in one tab, it automatically updates value in all other opened browser tabs.
You can test this feature by opening 2 tabs with Mantine docs side by side and changing color scheme
(button on the top right or ⌘ + J on MacOS and Ctrl + J on Windows and Linux).
Serialize/deserialize JSON
By default, hook will serialize/deserialize data with JSON.stringify/JSON.parse.
If you need to store data in local storage that cannot be serialized with JSON.stringify
– provide your own serialization handlers:
Usage with superjson
superjson is compatible with JSON.stringify/JSON.parse but works for Date, Map, Set and BigInt:
use-session-storage
use-session-storage hook works the same way as use-local-storage hook but uses window.sessionStorage instead of window.localStorage:
TypeScript
Definition
Set value type
You can specify value type same as in useState hook: