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.
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.
Similar Modules
Copy to Clipboard Button
React component that copies text to clipboard and shows a Copied! confirmation.
typescript
·
Beginner
Framer Motion Fade-In Wrapper
Reusable component that fades any child element in on mount.
typescript
·
Beginner
Compound Component Pattern
Implement a flexible Tabs component using React Context and compound component pattern.
typescript
·
Intermediate