Back to all snippets
Library/React/useLocalStorage Hook
typescriptintermediatehooksstoragestate

How to implement useLocalStorage Hook in Typescript

React hook for managing state synchronized with localStorage

Quick Answer

useLocalStorage is a drop-in replacement for useState that persists the value in localStorage. It initialises from stored data on mount and keeps storage in sync on every update, surviving page refreshes without any extra code.

Code Snippet

1import { useState, useEffect } from 'react';
2
3function useLocalStorage<T>(key: string, initialValue: T) {
4  const [storedValue, setStoredValue] = useState<T>(() => {
5    try {
6      const item = window.localStorage.getItem(key);
7      return item ? JSON.parse(item) : initialValue;
8    } catch (error) {
9      return initialValue;
10    }
11  });
12
13  const setValue = (value: T | ((val: T) => T)) => {
14    try {
15      const valueToStore = value instanceof Function ? value(storedValue) : value;
16      setStoredValue(valueToStore);
17      window.localStorage.setItem(key, JSON.stringify(valueToStore));
18    } catch (error) {
19      console.log(error);
20    }
21  };
22
23  return [storedValue, setValue] as const;
24}

What is useLocalStorage Hook?

This custom React hook wraps useState and keeps it in sync with localStorage automatically. It initializes from stored data on mount and persists every update, making it easy to build features like theme preferences, saved filters, or remembered form values that survive page refreshes.

How It Works

  1. 1The lazy initializer reads from localStorage so the initial render already has the persisted value.
  2. 2setValue accepts a direct value or an updater function, just like useState.
  3. 3The value is JSON-stringified before writing and parsed on read.
  4. 4All localStorage access is wrapped in try/catch to handle SSR or disabled storage gracefully.

Common Use Cases

  • Theme preference - Persist dark/light mode between visits
  • Filter state - Remember selected filters after navigation
  • Onboarding state - Track which steps a user has completed
  • Draft content - Auto-save form inputs locally

Key Benefits

  • Drop-in replacement for useState with automatic persistence
  • Handles JSON serialization and parsing automatically
  • Falls back gracefully if localStorage is unavailable
  • Works with any serializable state type

Common Mistakes to Avoid

  • Calling useLocalStorage during SSR where window is undefined — add a typeof window check.
  • Storing non-serialisable values like functions or class instances — they cannot be JSON-stringified.
  • Creating a new key per user without cleanup — old keys accumulate and waste storage quota.

Quick Tips

  • Click the "Copy" button above to copy the code to your clipboard
  • This code is production-ready and can be used in your projects immediately
  • Check out related snippets below for more typescript examples

Frequently Asked Questions

Does useLocalStorage work with SSR in Next.js?

Add a typeof window !== 'undefined' guard inside the lazy initializer, or conditionally call the hook only on the client.

How is useLocalStorage different from useState?

It is identical in API but automatically persists the value to localStorage so it survives page refreshes and tab closures.

Can I share localStorage state between tabs?

Not automatically, but you can add a storage event listener to the window to pick up changes made in other tabs.

About This Typescript Code Snippet

This free typescript code snippet for uselocalstorage hook is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement uselocalstorage hook quickly and correctly.

All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.

Tags: hooks, storage, state  | Language: typescript  | Difficulty: intermediate  | Category: React

Build Your Own Snippet Library

Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.