All Projects → astoilkov → Use Local Storage State

astoilkov / Use Local Storage State

Licence: mit
React hook that persists data in local storage

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Use Local Storage State

React Storage Hooks
React hooks for persistent state
Stars: ✭ 146 (-62.76%)
Mutual labels:  persistent, localstorage
Kiero
Universal graphical hook for a D3D9-D3D12, OpenGL and Vulkan based games.
Stars: ✭ 374 (-4.59%)
Mutual labels:  hook
Vagrant Persistent Storage
A Vagrant plugin that creates a persistent storage and attaches it to guest machine.
Stars: ✭ 285 (-27.3%)
Mutual labels:  persistent
Monohook
hook C# method at runtime without modify dll file (such as UnityEditor.dll)
Stars: ✭ 348 (-11.22%)
Mutual labels:  hook
Javascript For Everyone
A step by step guide to learn JavaScript and programming
Stars: ✭ 285 (-27.3%)
Mutual labels:  localstorage
Anymethodlog
Log any method call of object in Objective-C
Stars: ✭ 361 (-7.91%)
Mutual labels:  hook
Epic
Dynamic java method AOP hook for Android(continution of Dexposed on ART), Supporting 5.0~11
Stars: ✭ 3,434 (+776.02%)
Mutual labels:  hook
Androididchanger
Xposed Module for Changing Android Device Info
Stars: ✭ 394 (+0.51%)
Mutual labels:  hook
Rbtray
A fork of RBTray from http://sourceforge.net/p/rbtray/code/.
Stars: ✭ 365 (-6.89%)
Mutual labels:  hook
Gelectron
gameoverlay solution for Electron, Qt and CEF, just like discord game overlay and steam game overlay, inject any app to overlay in your game
Stars: ✭ 317 (-19.13%)
Mutual labels:  hook
Angular Locker
🗄️ A simple & configurable abstraction for local/session storage in angular js projects
Stars: ✭ 318 (-18.88%)
Mutual labels:  localstorage
Use Editable
A small React hook to turn elements into fully renderable & editable content surfaces, like code editors, using contenteditable (and magic)
Stars: ✭ 291 (-25.77%)
Mutual labels:  hook
Use Onclickoutside
React hook for listening for clicks outside of an element.
Stars: ✭ 361 (-7.91%)
Mutual labels:  hook
Swr
React Hooks for data fetching
Stars: ✭ 20,348 (+5090.82%)
Mutual labels:  hook
Localforage
💾 Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.
Stars: ✭ 19,840 (+4961.22%)
Mutual labels:  localstorage
Laravel Setting
Persistent settings package for Laravel
Stars: ✭ 278 (-29.08%)
Mutual labels:  persistent
Androidcomponentplugin
Android上简单实现四大组件的插件化,供学习使用
Stars: ✭ 316 (-19.39%)
Mutual labels:  hook
Plthook
Hook function calls by replacing PLT(Procedure Linkage Table) entries.
Stars: ✭ 351 (-10.46%)
Mutual labels:  hook
Ng2 Webstorage
Localstorage and sessionstorage manager - Angular service
Stars: ✭ 395 (+0.77%)
Mutual labels:  localstorage
Wormhole
Wormhole — it's better EventEmitter for communication between tabs with supporting Master/Slave.
Stars: ✭ 393 (+0.26%)
Mutual labels:  persistent

use-local-storage-state

React hook that persist data in local storage

Build Status Test Coverage Minified Size Dependencies

Install

npm install use-local-storage-state

Why

Few other libraries also try to abstract the usage of localStorage into a hook. Here are the reasons why you would consider this one:

  • Uses JSON.parse() and JSON.stringify() to support non string values
  • Supports SSR
  • 100% test coverage. No istanbul ignore
  • Handles edge cases – example
  • Subscribes to the Window storage event which tracks changes across browser tabs and iframe's
  • High quality with my open-source principles

Usage

import useLocalStorageState from 'use-local-storage-state'

const [todos, setTodos] = useLocalStorageState('todos', [
    'buy milk',
    'do 50 push-ups'
])

Todo list example

You can experiment with the example here.

import React, { useState } from 'react'
import useLocalStorageState from 'use-local-storage-state'

export default function Todos() {
    const [query, setQuery] = useState('')
    const [todos, setTodos] = useLocalStorageState('todos', ['buy milk'])

    function onClick() {
        setQuery('')
        setTodos([...todos, query])
    }

    return (
        <>
            <input value={query} onChange={e => setQuery(e.target.value)} />
            <button onClick={onClick}>Create</button>
            {todos.map(todo => (<div>{todo}</div>))}
        </>
    )
}

Reseting to defaults

The setTodos.reset() method will reset the value to its default and will remove the key from the localStorage. It returns to the same state as when the hook was initially created.

import useLocalStorageState from 'use-local-storage-state'

const [todos, setTodos] = useLocalStorageState('todos', [
    'buy milk',
    'do 50 push-ups'
])

setTodos.reset()

Handling edge cases with isPersistent

There are a few cases when localStorage isn't available. The isPersistent property tells you if the data is persisted in local storage or in-memory. Useful when you want to notify the user that their data won't be persisted.

import React, { useState } from 'react'
import useLocalStorageState from 'use-local-storage-state'

export default function Todos() {
    const [todos, setTodos, isPersistent] = useLocalStorageState('todos', ['buy milk'])

    return (
        <>
            {todos.map(todo => (<div>{todo}</div>))}
            {!isPersistent && <span>Changes aren't currently persisted.</span>}
        </>
    )
}

API

useLocalStorageState(key, defaultValue?)

Returns [value, setValue, isPersistent]. The first two are the same as useState(). The third(isPersistent) determines if the data is persisted in localStorage or in-memory – example.

key

Type: string

The key used when calling localStorage.setItem(key)and localStorage.getItem(key).

⚠️ Be careful with name conflicts as it is possible to access a property which is already in localStorage that was created from another place in the codebase or in an old version of the application.

defaultValue

Type: any Default: undefined

The initial value of the data. The same as useState(defaultValue) property.

createLocalStorageStateHook(key, defaultValue?)

If you want to have the same data in multiple components in your code use createLocalStorageStateHook() instead of useLocalStorageState(). This avoids:

  • maintenance issues with duplicate code that should always be in sync
  • conflicts with different default values
  • key parameter misspellings
import { createLocalStorageStateHook } from 'use-local-storage-state'

// Todos.tsx
const useTodos = createLocalStorageStateHook('todos', [
    'buy milk',
    'do 50 push-ups'
])
function Todos() {
    const [todos, setTodos] = useTodos()
}

// Popup.tsx
import useTodos from './useTodos'
function Popup() {
    const [todos, setTodos] = useTodos()
}

key

Type: string

The key used when calling localStorage.setItem(key)and localStorage.getItem(key).

⚠️ Be careful with name conflicts as it is possible to access a property which is already in localStorage that was created from another place in the codebase or in an old version of the application.

defaultValue

Type: any Default: undefined

The initial value of the data. The same as useState(defaultValue) property.

Alternatives

These are the best alternatives to my repo I have found so far:

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].