Scenario: Real-time Logging
Learn how to build a unified logging system that captures state changes across your entire application.
#The Concept
One of SuperState's most powerful features is the ability to interact with the store **outside of React**. This makes it perfect for logging middleware or service-level tracking.
#Implementation
ts
logger.ts1import { initState, setState } from "react-use-superstate"
2
3// 1. Initialize a 'logs' key at module scope
4initState('logs', [])
5
6export const logEvent = (message: string, type: 'info' | 'error' = 'info') => {
7 setState('logs', (prev: any[]) => [
8 ...prev,
9 { id: Date.now(), message, type, timestamp: new Date() }
10 ])
11}
12
13// 2. Clear logs
14export const clearLogs = () => setState('logs', [])
#Consuming in UI
ts
LogViewer.tsx1import { useSuperState } from "react-use-superstate"
2
3export function LogViewer() {
4 const [logs] = useSuperState('logs')
5
6 return (
7 <div className="log-container">
8 {logs?.map(log => (
9 <div key={log.id} className={log.type}>
10 [{log.timestamp.toLocaleTimeString()}] {log.message}
11 </div>
12 ))}
13 </div>
14 )
15}
Production Logging
For production, you could extend this guide to sync
logs with an external service like Sentry or LogRocket within a batchUpdate block.Back FAQ