logo
Back to blogs

Enhancing State Management

Mar 10, 2023 - 5 min read

Enhancing State Management

Example of useLocalStorage Hook

App.tsx
1import React from "react"; 2import useLocalStorage from "./hooks/useLocalStorage"; 3const App = () => { 4 const [name, setName] = useLocalStorage < string > ("name", "Guest"); 5 return ( 6 <div> 7 <h1>Hello, {name}!</h1> 8 <input 9 type="text" 10 value={name} 11 onChange={(e)=> setName(e.target.value)} 12 /> 13 </div> 14 ); 15}; 16 17export default App;

Implementation :

useLocalStorage.ts
1import { useSyncExternalStore } from "react"; 2// Custom hook to manage local storage 3function useLocalStorage<T>(key: string, initialValue: T) { 4 // Get the current value from local storage or use the initial value 5 const getSnapshot = () => { 6 const item = window.localStorage.getItem(key); 7 return item ? JSON.parse(item) : initialValue; 8 }; 9 // Subscribe to storage events 10 const subscribe = (callback: () => void) => { 11 const handleStorageChange = (e: StorageEvent) => { 12 if (e.key === key) { 13 callback(); 14 } 15 }; 16 window.addEventListener("storage", handleStorageChange); 17 return () => window.removeEventListener("storage", handleStorageChange); 18 }; 19 // Use useSyncExternalStore to manage the subscription 20 const value = useSyncExternalStore(subscribe, getSnapshot); 21 // Set value in localStorage 22 const setValue = (newValue: T) => { 23 try { 24 const valueToStore = 25 newValue instanceof Function ? newValue(value) : newValue; 26 window.localStorage.setItem(key, JSON.stringify(valueToStore)); 27 } catch (error) { 28 console.error("Error writing to localStorage:", error); 29 } 30 }; 31 return [value, setValue] as const; 32} 33export default useLocalStorage;