Skip to content

Instantly share code, notes, and snippets.

@Luisgustavom1
Created September 8, 2022 01:26
Show Gist options
  • Save Luisgustavom1/8f7a3c347055796cf6b144af9cfed8bc to your computer and use it in GitHub Desktop.
Save Luisgustavom1/8f7a3c347055796cf6b144af9cfed8bc to your computer and use it in GitHub Desktop.
Hook to use states based in local storage
import React from 'react'
export const useLocalStorage = <T extends string | object>(
item: string,
initialValue = '',
): [string, React.Dispatch<(value: T) => T>] => {
const [localStorageItem, setLocalStorageItem] = React.useState(() => {
const itemStoraged = localStorage.getItem(item)
if (itemStoraged) {
return JSON.parse(itemStoraged)
}
return initialValue
})
const storeItem = (fn: (value: T) => T) => {
const valueToStore = fn(localStorageItem)
setLocalStorageItem(valueToStore)
localStorage.setItem(item, JSON.stringify(valueToStore))
}
return [localStorageItem, storeItem]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment