Docs

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.ts
import { initState, setState } from "react-use-superstate"
// 1. Initialize a 'logs' key at module scope
initState('logs', [])
export const logEvent = (message: string, type: 'info' | 'error' = 'info') => {
setState('logs', (prev: any[]) => [
...prev,
{ id: Date.now(), message, type, timestamp: new Date() }
])
}
// 2. Clear logs
export const clearLogs = () => setState('logs', [])

#Consuming in UI

ts
LogViewer.tsx
import { useSuperState } from "react-use-superstate"
export function LogViewer() {
const [logs] = useSuperState('logs')
return (
<div className="log-container">
{logs?.map(log => (
<div key={log.id} className={log.type}>
[{log.timestamp.toLocaleTimeString()}] {log.message}
</div>
))}
</div>
)
}
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