跪拜 Guibai
← All articles
Frontend · Backend

Zustand and localStorage Aren't Redundant — They Solve Two Halves of Auth State

By 东风破_ ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Mixing persistence and reactive state is a common source of bugs in React auth flows. Treating localStorage as the durable layer and Zustand as the runtime layer eliminates stale UI and prop-drilling without over-engineering.

Summary

React components need to know whether a user is logged in, but localStorage alone won't trigger re-renders. Zustand provides a global store that any component can subscribe to, making auth state immediately reactive across the UI. The store initializes by reading persisted tokens from localStorage, then keeps the two layers synchronized on login and logout. The pattern separates concerns cleanly: localStorage survives refreshes, Zustand drives the live React state. A single `setAuth` call updates both the store and localStorage, and a `logout` action clears both, returning the app to an unauthenticated state.

Takeaways
localStorage persists a token across page refreshes but does not trigger React re-renders.
Zustand holds auth state in memory so any subscribing component re-renders when login status changes.
The store initializes token and user from localStorage to survive a full page reload.
user objects must be serialized with JSON.stringify before storage and parsed with JSON.parse on retrieval.
A single setAuth action updates both the Zustand store and localStorage, keeping them in sync.
A logout action clears both the store and localStorage, resetting the app to an unauthenticated state.
Components like Nav read auth state directly from the store via selectors, avoiding prop-drilling entirely.
Conclusions

Beginners often treat localStorage as the source of truth for auth, then wonder why the UI doesn't update — the missing piece is a reactive store that bridges persistence and rendering.

The Zustand create(set => ({})) pattern looks odd because it inverts control: you hand a factory function a setter, and Zustand wires up the subscription machinery behind the scenes.

Storing both a token and a parsed user object in the store is a pragmatic choice that avoids repeated deserialization and lets components consume identity data directly.

Concepts & terms
Zustand
A small, fast state-management library for React that uses a single store created via a function receiving a set callback, letting components subscribe to slices of state through selectors.
localStorage
A browser Web Storage API that persists key-value string pairs across page sessions and reloads, but provides no reactivity — changes do not notify running JavaScript code.
Source: juejin.cn ↗ Google Translate ↗ Backup ↗