Skip to content

Instantly share code, notes, and snippets.

@YussufElarif
Last active January 8, 2021 13:25
Show Gist options
  • Save YussufElarif/c30780ed3595695b7f73ea91db468159 to your computer and use it in GitHub Desktop.
Save YussufElarif/c30780ed3595695b7f73ea91db468159 to your computer and use it in GitHub Desktop.
React useStorage localStorage hook
export function useStorage<T>(key: string)
{
function getKey()
{
const data = localStorage.getItem(key);
if (!data)
{
return;
}
// "as T" used instead of "<T>". React throws a warning if "<T>" is used.
return JSON.parse(data) as T;
}
function setKey(body: T)
{
localStorage.setItem(key, JSON.stringify(body));
}
function deleteKey()
{
localStorage.removeItem(key);
}
return {
getKey,
setKey,
deleteKey
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment