usePersistedState

Use persisted state as a drop in replacement for Reacts built-in hook useState.

By default it will use the key local-storage-hook. But you probably want to set another key if you plan to use this hook on several places across your application.

Any changes to state will be emitted both across your application and across instances of you application running in other windows/tabs.

Usage

import React from 'react';
import { usePersistedState } from '@fransvilhelm/hooks';
const Counter = () => {
const [count, setCount] = usePersistedState(0, 'counter');
return (
<div>
<button onClick={() => setCount(count - 1)}>-</button>
<output>{count}</output>
<button onClick={() => setCount(count + 1)}>+</button>
</div>
);
};

Example

Open this same page in another tab and increase or decrease the counter and see how this is emitted between pages.

Also the counters below share the same persisted state and changes to one component will be emitted to an other component using the same key.

And if you refresh the page, the last count will be persisted.

0
0

Parameters

usePersistedState accepts two arguments, the default initial state and a key to store the state on (preferably unique across your application).

ParamTypeRequiredDefaultDescription
initialStateS | () => Strue-Default initial state, if non is found on localStorage
keystringfalselocal-storage-hookKey to persist value to

Returns

usePersistedState returns an array tuple, similar to useState. The first value is the current state, the second is a state updater function.

IndexItemTypeDescription
0stateSCurrent state
1setStatefunctionA state updater function, accepts either a number or a factory function retrieving the current state and returns a new state