npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-use-localstate

v1.1.0

Published

A lightweight, type-safe custom React hook to sync state with localStorage.

Readme

react-use-localstate

A lightweight, type-safe custom React hook that seamlessly synchronizes React state with localStorage. It behaves exactly like React's native useState, but persists data across page refreshes.

Features

  • Zero Dependencies: Ultra-lightweight and fast.
  • 🔄 Native-Like API: Drop-in replacement for useState.
  • 🔒 Type Safe: Written in TypeScript with full generics support.
  • 🧼 SSR Friendly: Safe for use in Next.js or Remix environments (won't crash on server-side rendering).
  • 🗃️ Functional Updates: Supports functional state updates like setValue(prev => !prev).

📦 Installation

npm install react-use-localstate

🚀 Quick Start

import { useLocalState } from 'react-use-localstate';

export default function App() {
  const [count, setCount] = useLocalState('count', 0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(0)}>Reset</button>
    </div>
  );
}

The count state will persist across page refreshes!

📖 Usage

Basic String State

const [name, setName] = useLocalState('userName', 'Guest');

return (
  <input
    value={name}
    onChange={(e) => setName(e.target.value)}
    placeholder="Enter your name"
  />
);

Complex Objects

const [user, setUser] = useLocalState('user', {
  id: 1,
  name: 'John',
  preferences: { theme: 'dark' }
});

// Update entire object
setUser({ ...user, name: 'Jane' });

// Or use functional updates
setUser(prev => ({ ...prev, name: 'Jane' }));

Arrays

const [todos, setTodos] = useLocalState('todos', []);

const addTodo = (text) => {
  setTodos([...todos, { id: Date.now(), text }]);
};

const removeTodo = (id) => {
  setTodos(todos.filter(todo => todo.id !== id));
};

Lazy Initialization

// Use a function for expensive initial computations
const [data, setData] = useLocalState('data', () => {
  return fetchExpensiveData(); // Only called on first mount
});

Form State Management

const [formData, setFormData] = useLocalState('form', {
  email: '',
  password: '',
  rememberMe: false
});

const handleChange = (e) => {
  const { name, value, type, checked } = e.target;
  setFormData(prev => ({
    ...prev,
    [name]: type === 'checkbox' ? checked : value
  }));
};

📚 API Documentation

useLocalState

A custom React hook that synchronizes state with localStorage.

Signature:

function useLocalState<T>(
  key: string,
  initialValue: T | (() => T)
): [T, Dispatch<SetStateAction<T>>]

Parameters:

  • key (string, required): The localStorage key to persist the value under.
  • initialValue (T | function, required): The initial state value. Can be a direct value or a function that returns the initial value (lazy initialization).

Returns:

A tuple containing:

  • value (T): The current state value from localStorage (or initialValue if not found).
  • setValue (function): A function to update the state, exactly like useState.

Type Safety:

The hook is fully generic and TypeScript will infer the type based on the initial value:

const [count, setCount] = useLocalState('count', 0); // T is number
const [name, setName] = useLocalState('name', 'John'); // T is string
const [items, setItems] = useLocalState('items', [] as Item[]); // T is Item[]

Error Handling:

The hook gracefully handles localStorage errors:

  • If localStorage is not available, it silently falls back to the initial value.
  • Parse errors are logged to console but won't crash your app.
  • SSR-safe: Returns the initial value during server-side rendering.

🌐 Browser Support

Works in all modern browsers that support:

  • localStorage API
  • ES6+ JavaScript
  • React 18+

Gracefully degrades in environments without localStorage (SSR, older browsers).

⚠️ Important Notes

  • Storage Limit: localStorage has a ~5-10MB limit per domain
  • Sensitive Data: Don't store passwords or tokens in localStorage. Use httpOnly cookies for authentication.
  • Performance: Avoid storing very large objects as it will impact localStorage performance
  • Synchronization: Changes from other tabs/windows won't automatically sync (consider using storage events for that)

🤝 Contributing

We welcome contributions! If you'd like to contribute to react-use-localstate, please follow our Contribution Guidelines.

Development Setup

# Install dependencies
npm install

# Run tests
npm test

# Run tests in watch mode
npm run test:watch

# Build the library
npm run build

Author

Subramanya KS

License

This project is licensed under the MIT License - see the LICENSE file for details.