use-local-storage | Mantine

Exposes localStorage value as react state, syncs state across opened tabs

The use-local-storage hook allows you to use a value from localStorage as React state. The hook works the same way as useState , but also writes the value to localStorage :

Example of a color scheme toggle button that uses use-local-storage hook to store current color scheme in the localStorage :

Use removeValue callback to clean localStorage / sessionStorage . When value is removed it is reset to defaultValue :

use-local-storage subscribes to storage event . When state changes in one tab, it automatically updates the value in all other opened browser tabs. You can test this feature by opening 2 tabs with Mantine docs side by side and changing the color scheme (button on the top right or ⌘ + J on MacOS and Ctrl + J on Windows and Linux).

By default, the 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:

superjson is compatible with JSON.stringify / JSON.parse but works for Date , Map , Set and BigInt :

The use-session-storage hook works the same way as use-local-storage hook but uses sessionStorage instead of window.localStorage :

You can specify value type same as in useState hook:

To read value from storage without using hook, use readLocalStorageValue / readSessionStorageValue functions. Functions accept the same arguments as use-local-storage / use-session-storage hooks:

UseStorageOptions and UseStorageReturnValue types are exported from the @mantine/hooks package; you can import them in your application:

Recommended articles