A react hook for easily storing app data to local or session storage.
npm i[nstall] use-persist
useHooks
requires requires two arguments, the data you want to persist and a configuration object.
- data (required
any
) - The data to be stored. - config (required
UsePersistConfig
)name
(requiredstring
) - The name that will be used as a key in local/session storageonMount
(required(data: any) => void
) - A function that will be called when the component mounts. This is where you can rehydrate your component's statedebounceTime
(optionalnumber
defaults to300
) - The length of time (in milliseconds) a persist is debounced before actually saving the data.useSessionStorage
(optionalboolean
default tofalse
) - Set to true to usesessionStorage
instead oflocalStorage
skip
(optionalboolean
defaults tofalse
) - Set totrue
to skip both the saving and hydration of data.
A simple example with only the required arguments
const SimplePersist = () => {
const [myData, setMyData] = useState({});
usePersist(myData, {
name: 'myData',
onMount: setMyData,
});
};
A more complicated example implementing the optional arguments
const SimplePersist = () => {
const [myData, setMyData] = useState({});
const [disabled, setDisabled] = useState(false);
usePersist(myData, {
name: 'myData',
onMount: setMyData,
useSessionStorage: true,
skip: disabled,
debounceTime: 500,
});
};