React Use Window.localStorage
Edit page
Home
Hooks
useClearLocalStorageuseLocalStorageBooleanuseLocalStorageItemuseLocalStorageNumberuseLocalStorageObjectDescriptionUsageSignatureExampleuseLocalStorageString
Code of ConductMIT License

useLocalStorageObject

Description

This hook gets and sets an Object in localStorage. This includes arrays.

Uses JSON.stringify() and JSON.parse() for string encoding, so make sure your object is compatible with that interface. For objects that JSON.stringify() can't handle, provide your own encoding via useLocalStorageItem.

Features synchronization across hooks sharing the same key name.

Usage

import { useLocalStorageObject } from 'react-use-window-localstorage';

In your function component:

const [value, setValue] = useLocalStorageObject('myObj', { a: 'hello', b: 123 });

The hook takes a key name and an optional default value argument. The default value will be immediately written to localStorage and returned if no value is present already. Uses null when no default value is provided.

Use value and setValue to read and write the value.

Because localStorage accepts strings only, the value is encoded using JSON.stringify() and decoded using JSON.parse(). Make sure your object is compatible with that interface.

Additional Features

The hook provides additional features in its return array, should you be interested:

const [value, setValue, loading, available, reset] = useLocalStorageObject('myObj', { a: 'hello', b: 123 });
  • A loading value of true indicates that the value is being loaded from localStorage.
  • An available value of true indicates that localStorage is supported and available for use.
  • The reset() function sets the value back to the provided default, or null if none was given.

Signature

useLocalStorageObject(keyName: string, defaultValue?: Object | null) => [Object | null, (value: Object | null) => void, boolean, () => void, () => void]

Props

PropTypeDescription
keyNamestringRequired. Key name to use in localStorage.
defaultValueObject | nullOptional. Provide a default Object value when the key's value is not found in localStorage. Will be immediately written to localStorage if not present. Use null for no default.

Return

The hook returns an array containing:

IndexNameTypeDescription
0valueObject | nullThe Object value from localStorage, when loading is false. Will be the default value (or null if none provided) while loading is true. If null when not loading, the key was not found in localStorage.
1setValue(value: Object | null) => voidSets the value in localStorage. Provide null to set it back to the default value. Providing null will delete the key from localStorage if the default value is null.
2loadingbooleantrue while the value loads from localStorage, false otherwise.
3availablebooleantrue if localStorage is supported and available for use, false otherwise.
4reset() => voidReset the value to the default.

Example


import * as React from 'react';
import { useLocalStorageObject } from 'react-use-window-localstorage';
export function UseLocalStorageObjectExample() {
const defaultValue = { first: 'Ron', last: 'Burgundy' };
const [enteredFirstName, setEnteredFirstName] = React.useState(defaultValue.first);
const [enteredLastName, setEnteredLastName] = React.useState(defaultValue.last);
const enteredObj = { first: enteredFirstName, last: enteredLastName };
const [value, setValue, loading, available, reset] = useLocalStorageObject('objValue', defaultValue);
const [value2, setValue2, loading2] = useLocalStorageObject('objValue', defaultValue);
return (
<div>
{!loading && (
<div>
<div>
Key "objValue": {'{'} first:
<input
type="text"
value={enteredFirstName}
onChange={e => setEnteredFirstName(e.target.value)}
onKeyPress={e => e.key === 'Enter' && setValue(enteredObj)}
/>
, last:
<input
type="text"
value={enteredLastName}
onChange={e => setEnteredLastName(e.target.value)}
onKeyPress={e => e.key === 'Enter' && setValue(enteredObj)}
/>
{' } '}
<button onClick={() => setValue(enteredObj)}>Set</button>
</div>
<div>
<strong>Stored value:</strong> {JSON.stringify(value)}
</div>
</div>
)}
<div>
<button onClick={() => reset()}>Reset "objValue" to default</button>
</div>
<hr />
{!loading2 && <div>Another "objValue" hook (different hook, will synchronize): {JSON.stringify(value2)}</div>}
</div>
);
}