useLocalStorage persists state vào localStorage, tự đồng bộ khi value thay đổi.
js
function useLocalStorage(key, initial) {
const [value, setValue] = useState(() => {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : initial;
} catch { return initial; }
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}Test khả năng viết custom hooks với side effects.
function useLocalStorage(key, initial) { const [value, setValue] = useState(() => { try { const item = localStorage.getItem(key); return item ? JSON.parse(item) : initial; } catch { return initial; } }); useEffect(() => { localStorage.setItem(key, JSON.stringify(value)); }, [key, value]); return [value, setValue]; } Tests the ability to write custom hooks with side effects.