Frontend Blocks typescript Intermediate

useLocalStorage Hook

Typed React hook that syncs state with localStorage and handles SSR safely.

typescript
import { useState } from 'react';
export function useLocalStorage(key, initial) {
  const [stored, setStored] = useState(() => {
    if (typeof window === 'undefined') return initial;
    try { return JSON.parse(localStorage.getItem(key)) || initial; }
    catch { return initial; }
  });
  const setValue = (value) => {
    setStored(value);
    localStorage.setItem(key, JSON.stringify(value));
  };
  return [stored, setValue];
}

Prerequisites

  • React >= 17

Pro Tips

  • → Guard with typeof window for Next.js SSR.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
typescript
Level
Intermediate
Read time
2 min
Published
Oct 2024
License
Commercial License

Newsletter

New modules every week, directly to your inbox.