GithubHelp home page GithubHelp logo

vrease / use-local-storage-state Goto Github PK

View Code? Open in Web Editor NEW

This project forked from astoilkov/use-local-storage-state

1.0 0.0 0.0 103 KB

React hook that persist data in local storage

License: MIT License

TypeScript 99.62% JavaScript 0.38%

use-local-storage-state's Introduction

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.
  • SSR. Supports server-side rendering.
  • Well tested. 100% coverage.
  • Handles edge cases – example.
  • Subscribes to the Window storage event which tracks changes across browser tabs and iframe's.

Usage

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

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

Todo list

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() {
        setTodos([...todos, query])
    }

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

Using the same hook in multiple places

// store.ts
import { createLocalStorageStateHook } from 'use-local-storage-state'
const useTodos = createLocalStorageStateHook('todos', [
    'buy milk',
    'do 50 push-ups'
])
export default useTodos

// Todos.ts
import useTodos from '../store'
function Todos() {
    const [todos, setTodos] = useTodos()
}

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

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>}
        </>
    )
}

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()

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?)

Returns a hook to be used in multiple places – 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.

use-local-storage-state's People

Contributors

astoilkov avatar rexxars avatar vrease avatar

Stargazers

Roman avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.