import { useState, useEffect } from 'react'; function useLocalStorage(key, initialValue) { // State to store our value // Pass initial state function to useState so logic is only executed once const [storedValue, setStoredValue] = useState(() => { try { const item = window.localStorage.getItem(key); // Parse stored json or if none return initialValue return item ? JSON.parse(item) : initialValue; } catch (error) { // If error also return initialValue console.error(error); return initialValue; } }); // useEffect to update local storage when the state changes useEffect(() => { try { window.localStorage.setItem(key, JSON.stringify(storedValue)); } catch (error) { console.error(error); } }, [key, storedValue]); // Only re-call effect if key or storedValue changes return [storedValue, setStoredValue]; } // Example Usage: // function ThemeSwitcher() { // const [theme, setTheme] = useLocalStorage('app-theme', 'light'); // const toggleTheme = () => { // setTheme(theme === 'light' ? 'dark' : 'light'); // }; // return ( //
//

Current theme: {theme}

// //
// ); // }