Published

React useLocalStorageState

Authors
  • avatar
    Name
    xNoJustice

Custom hooks to use local storage state

import { useState, useEffect } from 'react'

export let useLocalStorageState = (key, defaultValue = '', options = {}) => {
  let { serialize = JSON.stringify, deserialize = JSON.parse } = options
  let [state, setState] = useState(() => {
    let valueInLocalStorage = window.localStorage.getItem(key)
    if (valueInLocalStorage) {
      return deserialize(valueInLocalStorage)
    }
    return defaultValue
  })

  useEffect(() => {
    window.localStorage.setItem(key, serialize(state))
  }, [key, state, serialize])

  return [state, setState]
}