Back to library
⚛️Reacttypescriptintermediate

useLocalStorage Hook

React hook for syncing state with localStorage

hooksstoragestate-management

Code

1import { useState, useEffect } from 'react';
2
3function useLocalStorage<T>(key: string, initialValue: T) {
4  // Get initial value from localStorage or use provided initial value
5  const [storedValue, setStoredValue] = useState<T>(() => {
6    try {
7      const item = window.localStorage.getItem(key);
8      return item ? JSON.parse(item) : initialValue;
9    } catch (error) {
10      console.error(error);
11      return initialValue;
12    }
13  });
14
15  // Update localStorage when state changes
16  useEffect(() => {
17    try {
18      window.localStorage.setItem(key, JSON.stringify(storedValue));
19    } catch (error) {
20      console.error(error);
21    }
22  }, [key, storedValue]);
23
24  return [storedValue, setStoredValue] as const;
25}
26
27// Usage example
28function App() {
29  const [name, setName] = useLocalStorage('name', 'Guest');
30  
31  return (
32    <div>
33      <input 
34        value={name} 
35        onChange={(e) => setName(e.target.value)} 
36      />
37      <p>Hello, {name}!</p>
38    </div>
39  );
40}

Quick Tips

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

Related Snippets

Build Your Own Snippet Library

Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.