Reactopia
BrowseDiscoverSVG toolsAIChangelogAboutContact
BrowseDiscoverSVG toolsAI
Created by

Yash Mahajan


Reactopia

Open React tooling: components, SVG animation, and a growing directory. Built by Yash Mahajan.

Product

  • Components
  • Discover
  • SVG tools
  • AI direction

Legal

  • Privacy Policy
  • Terms of Use
  • Cookie Policy
  • License
  • Credits
  • Contact

Project

  • About
  • Changelog
  • GitHub
  • X

© 2026 Reactopia. All rights reserved.

PrivacyTermsCookies

Getting Started

IntroductionContributing

Components

SeparatorUiButtonBadgeStackUiInputIn devUiSelectIn devUiTextareaIn dev

Hooks

useDebounceuseLocalStorageuseMediaQueryuseMounted

Utilities

cngroupBysleep
Components
useLocalStorage

useLocalStorage

Persist React state in localStorage with SSR-safe reads.

LivehookReact, WebUpdated 2026-10-07MIT LicenseSource on GitHubReport Issue
Dependencies:npm install react
useDebounceuseMediaQuery

Introduction

Persist state in localStorage with a React state tuple. Skips writes on the server and syncs when the key changes.

Platform: React (browser). Dependencies: react only.

Hook

import { useCallback, useEffect, useState } from "react";
export function useLocalStorage<T>(
key: string,
initialValue: T
): [T, (value: T | ((prev: T) => T)) => void] {
const read = useCallback((): T => {
if (typeof window === "undefined") return initialValue;
try {
const raw = window.localStorage.getItem(key);
return raw != null ? (JSON.parse(raw) as T) : initialValue;
} catch {
return initialValue;
}
}, [key, initialValue]);
const [stored, setStored] = useState<T>(read);
useEffect(() => {
setStored(read());
}, [read]);
const setValue = useCallback(
(value: T | ((prev: T) => T)) => {
setStored((prev) => {
const next = typeof value === "function" ? (value as (p: T) => T)(prev) : value;
try {
window.localStorage.setItem(key, JSON.stringify(next));
} catch {
// quota or private mode
}
return next;
});
},
[key]
);
return [stored, setValue];
}

Example

const [theme, setTheme] = useLocalStorage<"light" | "dark">("theme", "dark");

Footer

For sensitive data, do not use localStorage. Prefer httpOnly cookies or server sessions.

tsx