use-storage-backed-state
TypeScript icon, indicating that this package has built-in type declarations

1.2.0 • Public • Published

useStorageBackedState npm npm type definitions

Custom React hook for storage backed persisted state. Check interactive demo.

Installation

npm install use-storage-backed-state

How to use

import React from 'react'
import { useStorageBackedState } from 'use-storage-backed-state'

export const MyComponent = () => {
	// 0: initialState
	// 'count': localStorage key
	const [count, setCount] = useStorageBackedState(0, 'count')

	return (
		<section>
			<h1>
				Value: <output>{count}</output>
			</h1>
			<button
				onClick={() => {
					setCount(count + 1)
				}}
			>
				increment
			</button>
			<button
				onClick={() => {
					setCount(count - 1)
				}}
			>
				decrement
			</button>
		</section>
	)
}

example

Notes

  • Stores data in localStorage.

  • Works with sessionStorage too.

    useStorageBackedState(, , sessionStorage)
  • Realtime synchronization between multiple uses with the same key. Even across tabs.

  • You can opt out from storage and synchronization by passing null as the second argument or by omitting the key altogether. useStorageBackedState will then behave similarly like useState in that case.

    const [count, setCount] = useStorageBackedState(1)
    const [storeState, setStoreState] = useState(false)
    const [count, setCount] = useStorageBackedState(
    	1,
    	storeState ? 'count' : null,
    )

Package Sidebar

Install

npm i use-storage-backed-state

Weekly Downloads

109

Version

1.2.0

License

ISC

Unpacked Size

25.2 kB

Total Files

8

Last publish

Collaborators

  • onset