Created
September 8, 2022 01:26
-
-
Save Luisgustavom1/8f7a3c347055796cf6b144af9cfed8bc to your computer and use it in GitHub Desktop.
Hook to use states based in local storage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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