8000 GitHub - highlander08/useLocalstorage
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

highlander08/useLocalstorage

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 

Repository files navigation

useLocalstorage

/* eslint-disable no-console / / eslint-disable react-hooks/exhaustive-deps */

import { useState, useEffect } from "react";

export const useLocalStorage = (key: string, initialValue: T) => { const [storedValue, setStoredValue] = useState<T | undefined>();

const setValue = (value: T) => { window.localStorage.setItem(key, JSON.stringify(value)); };

useEffect(() => { const value = window.localStorage.getItem(key);

if (value) {
  try {
    const parsed = JSON.parse(value) as T;
    setStoredValue(parsed);
  } catch (error) {
    console.log(error);
    setStoredValue(initialValue);
  }
} else {
  setStoredValue(initialValue);
}

}, []);

useEffect(() => { if (storedValue) { setValue(storedValue); } }, [storedValue]);

return [storedValue as T, setStoredValue] as const; };

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published
0