Return to site

🧠💾 REACT: A PRACTICAL useLocalStorage HOOK

· react,programmmer

🔸 TLDR

▪️ A useLocalStorage hook keeps your React state persistent by reading from localStorage on init and writing back on updates ✅

▪️ Perfect for theme, feature flags, filters, UI preferences (and more) 🎨

▪️ Add a couple of safeguards and it becomes production-friendly 🛡️

Section image

🔸 WHAT IT DOES

const useLocalStorage = (key, initial) =〉{

const [value, setValue] = useState(() =〉

JSON.parse(localStorage.getItem(key)) || initial

);

useEffect(() =〉 {

localStorage.setItem(key, JSON.stringify(value));

}, [value]);

return [value, setValue];

};

▪️ On first render, it tries: localStorage.getItem(key) → JSON.parse(...) → fallback to initial

▪️ Every time value changes, it does: localStorage.setItem(key, JSON.stringify(value))

▪️ Result: state survives refresh, tab close, and browser restart 🔁

🔸 A SLIGHTLY SAFER VERSION (REAL WORLD READY)

import { useEffect, useState } from "react";

export function useLocalStorage(key, initialValue) {

const isBrowser = typeof window !== "undefined";

const [value, setValue] = useState(() =〉 {

if (!isBrowser) return initialValue;

try {

const stored = window.localStorage.getItem(key);

return stored !== null ? JSON.parse(stored) : initialValue;

} catch {

return initialValue; // corrupted JSON / blocked storage

}

});

useEffect(() =〉 {

if (!isBrowser) return;

try {

window.localStorage.setItem(key, JSON.stringify(value));

} catch {

// storage full / blocked (private mode / policies)

}

}, [key, value, isBrowser]);

return [value, setValue];

}

🔸 WHEN YOU’LL USE IT

▪️ Dark mode / UI density / language 🌙

▪️ Search filters & sorting (so users don’t lose context) 🔎

▪️ “Don’t show again” banners / onboarding steps 🧭

▪️ Small offline-friendly drafts (careful with size) 📝

🔸 COMMON PITFALLS (DON’T GET BITTEN)

▪️ ⚠️ SSR (Next.js): window doesn’t exist on the server → guard it

▪️ ⚠️ JSON parsing: corrupted value can crash the render → wrap in try/catch

▪️ ⚠️ Security: avoid storing secrets/tokens in localStorage (XSS risk) 🔐

▪️ ⚠️ Cross-tab sync: another tab can change the value → consider listening to the "storage" event

▪️ ⚠️ Quota/blocked storage: private mode / enterprise policies / full storage → fail gracefully

🔸 TAKEAWAYS

▪️ useLocalStorage is a tiny hook that massively improves UX ✨

▪️ Production version = SSR guard + try/catch + graceful failures 🧰

▪️ Store preferences, not secrets ✅

#React #JavaScript #Frontend #WebDev #Hooks #localStorage #UX #NextJS #TypeScript