0.0.0 • Published 5 years ago

use-cached-state v0.0.0

Weekly downloads
1
License
MIT
Repository
-
Last release
5 years ago

use-cached-state

A cached and optionally persisted alternative to useState.

npm version

Features

💰 Caches state values even after your component unmounts.

💰 Optionally persists to localStorage.

💰 Shares values between components on the same page and even in different browser tabs!

Installation

$ npm i use-cached-state

or

$ yarn add use-cached-state

Usage

Here is a basic setup. Perform the following from within your module, but not in your component. This will create a custom Hook that you can then use in your component.

const useCachedState = createCachedState(config);

Next, from without your component, do this (instead of useState).

const [state, setState] = useCachedState(options);

Parameters

createCachedState is passed a single config object with the following properties.

ParameterDescription
namespaceA required string that will be used as a namespace.
storageProviderA storage provider to use. The default is null which specifies NOT to persist to storage (i.e. just cache in memory). The storage provider must provide a getItem and a setItem method. You may use localStorage or sessionStorage or your own custom storage provider.

Return

createCachedState returns a custom Hook that you can use from within your component. This custom Hook accepts an options object with the following properties.

PropertyDescription
keyA optional string that represents the key to use for this instance of the component. If all instances are to share the same state, pass the same key (or use the default).
initialValueThis will be the initial value used.

Example

TODO provide examples here.

Prior art

This is the next generation of my own use-persisted-state package. It was inspired by a tweet from Ryan Florence.

License

MIT Licensed

Contributors

Thanks goes to these wonderful people (emoji key):

This project follows the all-contributors specification. Contributions of any kind welcome!