Docs

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.ts
import { initState, setState } from "react-use-superstate"
// 1. Initialize global auth state at module scope (outside React)
initState('authUser', null)
// 2. Login functionupdates state from anywhere
export const login = (userData: any) => {
setState('authUser', userData)
}
// 3. Logout function
export const logout = () => {
setState('authUser', null)
}

#Multi-component Sync

Navbar.tsx

ts
app/page.tsx
const [user] = useSuperState('authUser')
return user ? <Avatar /> : <LoginButton />

Settings.tsx

ts
app/page.tsx
const [user, setUser] = useSuperState('authUser')
return <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.