1.1.3 • Published 4 months ago

use-storage-backed-state v1.1.3

Weekly downloads
7
License
ISC
Repository
github
Last release
4 months ago

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,
    )
1.1.1

4 months ago

1.1.0

4 months ago

1.1.3

4 months ago

1.1.2

4 months ago

1.0.4

5 months ago

1.0.2

6 months ago

1.0.1

6 months ago

1.0.0

6 months ago

1.0.3

6 months ago

0.2.4

1 year ago

0.2.3

2 years ago

0.2.1

3 years ago

0.2.2

3 years ago

0.2.0

3 years ago

0.1.0

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.1

3 years ago