useLocalStorage

React hook to manage localStorage

useLocalStorage is a custom hook used to get and set values in localStorage. The value is stored as JSON. The state will be updated across browser tabs, thanks to Window: storage event.

Import

import { useLocalStorage } from '@saas-ui/react'

Parameters

NameTypeDescription
keystringThe local storage key.
defaultValueObject, string, number, boolean, null, undefinedThe default value for this key.
optionsserializer and deserializerUse a custom serializer

Usage

The useLocalStorage hook returns a tuple with the value and a setValue function, similar to useState

const [value, setValue] = useLocalStorage(key, defaultValue)

Example usage

function Example() {
const [value, setValue] = useLocalStorage('app.example', { count: 0 })
return (
<>
<Button onClick={() => setValue({ count: value.count + 1 })}>
Count: {value.count}
</Button>
</>
)
}

Was this helpful?