Last active
January 11, 2024 22:57
-
-
Save sandroweb/996bdae8cb8816a841d69e52524abb7c to your computer and use it in GitHub Desktop.
A React Hook to manage LocalStorage items with generic type, with set, refresh and remove actions.
This file contains 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 { useCallback, useMemo, useState } from 'react'; | |
export interface useLocalStorageProps<T> { | |
id: string; | |
defaultValue: T; | |
} | |
export interface useLocalStorageReturn<T> { | |
setValue: (value: T) => void; | |
value: T; | |
refresh: () => void; | |
remove: () => void; | |
} | |
export const useLocalStorage = <T>({ | |
id, | |
defaultValue, | |
}: useLocalStorageProps<T>): useLocalStorageReturn<T> => { | |
const [localStorageValue, setLocalStorageValue] = useState< | |
string | undefined | |
>(window.localStorage.getItem(id) || undefined); | |
const refresh = useCallback(() => { | |
return setLocalStorageValue( | |
window.localStorage.getItem(id) || undefined, | |
); | |
}, [id]); | |
const setValue = useCallback( | |
(value: T) => { | |
if (value) { | |
window.localStorage.setItem(id, JSON.stringify(value)); | |
refresh(); | |
} | |
}, | |
[id, refresh], | |
); | |
const remove = useCallback(() => { | |
window.localStorage.removeItem(id); | |
return refresh(); | |
}, [id, refresh]); | |
const value = useMemo<T>(() => { | |
return localStorageValue ? JSON.parse(localStorageValue) : defaultValue; | |
}, [localStorageValue, defaultValue]); | |
return { | |
setValue, | |
value, | |
refresh, | |
remove, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment