use-synced-storage
React Hook to manage {local,sessions,*}storage with syncing across components and tabs
Quick Start
import React from 'react';
import { useLocalStorage } from 'use-storage/src/index';
export const MyComponent: React.FunctionComponent = () => {
const [state, setState] = useLocalStorage('state', { count: 0 });
return (
<div>
state.count is {state.count}
<button onClick={() => setState({ count: (state.count) + 1 })}>++</button>
</div>
);
}
The state will sync across components and tabs
API
This module exports a createUseStorage
function as well as a useLocalStorage
and useSessionStorage
hook.
The storage hooks api take the following options:
type Options<T> = {
/** Customize encoding and decoding the object */
serializer?: Serializer<T>;
/** Time to live for entry in milliseconds */
ttl?: number;
/** Interval polling for updates in the background, this needs to be enabled for checking ttl didn't expire after the component rendered. Defaults to 1000 */
pollingInterval?: number | false;
/** Only check ttl when loading value and NOT periodically throughout the life of the component */
checkTtlOnlyOnLoad?: boolean;
};