Loading content…
Loading content…
Write a React custom hook named `useLocalStorage` in TypeScript. It must work like `useState`, persisting the variable's state inside the browser's localStorage and syncing changes across page reloads.
Expected Output
A hook helper `const [value, setValue] = useLocalStorage(key, initialValue)` that works across page renders.
Click to toggle the recommended code solution
Architectural Explanation
This hook uses lazy initialization inside useState to check for client execution, encapsulates JSON serializations in try-catch blocks, and implements setter functions supporting callback updates.Code Snippet
import { useState, useEffect } from "react";
export function useLocalStorage<T>(key: string, initialValue: T) {
const [state, setState] = useState<T>(() => {
if (typeof window === "undefined") return initialValue;
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.warn(error);
return initialValue;
}
});
const setValue = (value: T | ((val: T) => T)) => {
try {
const valueToStore = value instanceof Function ? value(state) : value;
setState(valueToStore);
if (typeof window !== "undefined") {
window.localStorage.setItem(key, JSON.stringify(valueToStore));
}
} catch (error) {
console.warn(error);
}
};
return [state, setValue] as const;
}How to pitch this solution during technical interviews
I build hooks like useLocalStorage by combining state with localStorage checks. To support Next.js/SSR environments, I run initial state setups inside lazy initializers, checking for window declarations before executing parsing logic.