react-use-localstorage-hook-v1
v1.0.3
Published
A lightweight React hook for managing localStorage state safely with JSON parsing and tab sync support.
Maintainers
Readme
⚡ react-use-localstorage-hook
A lightweight React hook for managing localStorage state safely. Features include:
- JSON parsing for stored values
- Safe usage in SSR (Server-Side Rendering) environments
- Live sync across multiple browser tabs
Functional updates support
🚀 Installation
npm install react-use-localstorage-hookor with Yarn:
yarn add react-use-localstorage-hook-v1⚙️ Usage
import React from "react";
import useLocalStorage from "react-use-localstorage-hook-v1";
function App() {
const [name, setName] = useLocalStorage("username", "Guest");
const [count, setCount] = useLocalStorage("counter", 0);
return (
<div>
<h1>Hello, {name}!</h1>
<button onClick={() => setName("Muhammad Naveed")}>Set Name</button>
<h2>Counter: {count}</h2>
<button onClick={() => setCount(prev => prev + 1)}>Increment</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}
export default App;📝 API
useLocalStorage(key, initialValue)
key: string— The localStorage key to read/writeinitialValue: any— Default value if no stored value is found
Returns: [storedValue, setValue]
storedValue: Current value in localStoragesetValue: Function to update the value. Can be called with a value or a function (prev) => newValue.
Example: Sync across tabs
The hook automatically listens to changes in other browser tabs:
const [theme, setTheme] = useLocalStorage("theme", "light");
// If you change the theme in one tab, all other tabs will update automatically
Example: Functional updates
const [counter, setCounter] = useLocalStorage("counter", 0);
// Increment counter safely
setCounter(prev => prev + 1);
✅ Features
- SSR safe (
windowcheck included) - JSON parsing and stringifying handled automatically
- Supports functional updates
- Auto-sync between browser tabs using the
storageevent
