Scenario: Auth Synchronization
A common challenge in React is keeping user session data in sync across headers, profiles, and protected routes.
#The Challenge
Using Prop Drilling or Context for Auth often leads to unnecessary re-renders or stale data when the session expires or the user updates their profile.
#The SuperState Solution
ts
authService.ts1import { initState, setState } from "react-use-superstate"
2
3// 1. Initialize global auth state at module scope (outside React)
4initState('authUser', null)
5
6// 2. Login function — updates state from anywhere
7export const login = (userData: any) => {
8 setState('authUser', userData)
9}
10
11// 3. Logout function
12export const logout = () => {
13 setState('authUser', null)
14}
#Multi-component Sync
Navbar.tsx
ts
app/page.tsx1const [user] = useSuperState('authUser')
2return user ? <Avatar /> : <LoginButton />
Settings.tsx
ts
app/page.tsx1const [user, setUser] = useSuperState('authUser')
2return <input value={user.name} onChange={...} />
Index-free Updates
Notice how
Settings.tsx can update the user name without knowing about the Navbar. SuperState handles the reactivity automatically.Back Logging Guide