UNPKG

alinea

Version:

[![npm](https://img.shields.io/npm/v/alinea.svg)](https://npmjs.org/package/alinea) [![install size](https://packagephobia.com/badge?p=alinea)](https://packagephobia.com/result?p=alinea)

37 lines (35 loc) 956 B
import "../../chunks/chunk-U5RRZUYZ.js"; // src/ui/hook/UseLocalStorage.ts import { useEffect, useState } from "react"; function useLocalStorage(key, initialValue) { const [storedValue, setStoredValue] = useState(initialValue); const setValue = (value) => { try { setStoredValue(value); if (typeof window !== "undefined") window.localStorage.setItem(key, JSON.stringify(value)); } catch (error) { console.log(error); } }; function initialize() { try { const item = window.localStorage.getItem(key); setStoredValue(item ? JSON.parse(item) : initialValue); } catch (error) { console.log(error); } } useEffect(() => { initialize(); window.addEventListener("storage", (event) => { if (event.storageArea === window.localStorage && event.key === key) { initialize(); } }); }, []); return [storedValue, setValue]; } export { useLocalStorage };