useLocalStorage Local Storage Hook

Last updated: 2026-11-02

useLocalStorage Local Storage Hook

useLocalStorage keeps the reads and writes of useState in sync with localStorage: it reads the stored value lazily during initialization and writes back to disk on every update, so the state survives a page reload. It is the textbook example of a custom hook wrapping a native browser API. The returned setter behaves exactly like the one from useState, so callers never need to learn a second API just to get persistence for free.

GroupComponent Patterns
KindHook
SinceReact 16.8

ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.

📝 Syntax

function useLocalStorage(key, initial) {
  const [value, setValue] = useState(() => {
    const saved = localStorage.getItem(key)      // lazy init: read only once
    return saved !== null ? JSON.parse(saved) : initial
  })
  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value))
  }, [key, value])
  return [value, setValue]
}

⚙️ Parameters

keyThe storage key in localStorage; prefix it with your app name to avoid collisions.
initialThe value used when nothing is stored locally; any JSON-serializable type is supported.

Returns:Returns a [value, setValue] tuple that works exactly like useState, except that reads and writes are persisted to localStorage automatically.

▶ Example

The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.

Output:

Clicking the button increases the counter and writes it to localStorage; after a reload or reopening the page the count is still there, and "Reset" brings it back to zero.

💡 Key Points

💡 Tip Pass a function to initialize so the value is read lazily, which avoids touching localStorage on every render — it is synchronous I/O and not cheap.
ℹ️ Info Store objects and arrays with JSON serialization, and defend the read with try/catch in case the stored value is dirty or was edited by hand.
⚠️ Warning localStorage is shared per origin and capped at roughly 5 MB, so sensitive data such as tokens should never be stored there in plain text.
More case studies coming soon.

📚 Related Tutorials

❓ FAQ

Q Will it throw under SSR?
A Yes, the server has no window and no localStorage. Guard the read with a typeof window check or move it into a useEffect.
Q How is it different from using useState directly?
A It adds one layer of persistence: the initial value comes from disk, every change is written back automatically, and the API stays identical to useState.
Q Why JSON.stringify when storing an object?
A localStorage can only hold strings; without serialization you would store "[object Object]" and could never restore the value.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏