Published on

useLocalStorageState

Custom hooks to use local storage state

import { useState, useEffect } from 'react'
export const useLocalStorageState = (key, defaultValue = '', options = {}) => {
const { serialize = JSON.stringify, deserialize = JSON.parse } = options
const [state, setState] = useState(() => {
const 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]
}