UNPKG

simple-react-ui-kits

Version:

A lightweight, customizable React UI component library built with TypeScript and Tailwind CSS

40 lines (37 loc) 1.53 kB
import { useState, useEffect } from 'react'; /** * Custom hook for localStorage functionality * @param key - localStorage key * @param initialValue - Initial value if key doesn't exist * @returns [storedValue, setValue] - Current value and setter function */ export function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T | ((val: T) => T)) => void] { // Get from local storage then parse stored json or return initialValue const [storedValue, setStoredValue] = useState<T>(() => { if (typeof window === 'undefined') { return initialValue; } try { const item = window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { console.error(`Error reading localStorage key "${key}":`, error); return initialValue; } }); // Return a wrapped version of useState's setter function that persists the new value to localStorage const setValue = (value: T | ((val: T) => T)) => { try { // Allow value to be a function so we have the same API as useState const valueToStore = value instanceof Function ? value(storedValue) : value; setStoredValue(valueToStore); // Save to local storage if (typeof window !== 'undefined') { window.localStorage.setItem(key, JSON.stringify(valueToStore)); } } catch (error) { console.error(`Error setting localStorage key "${key}":`, error); } }; return [storedValue, setValue]; }