Course contentsShow
← React
Lesson 1765 of 2,39641. State Management EcosystemFree lesson

Valtio Outside Components: Global State

Using Valtio state in vanilla JS, utils, or event handlers without hooks, then syncing to components.

Valtio Outside Components: Global State

What you'll learn: How to use Valtio state in vanilla JavaScript functions, utilities, and event handlers outside of React components, while keeping your UI in sync.

The Power of Non-React Access

One of Valtio's biggest strengths is that your proxy state lives outside React's lifecycle entirely. Because it's just a plain JavaScript object wrapped in a proxy, you can import and mutate it from anywhere—vanilla JS utility functions, WebSocket handlers, timers, or even old-school event listeners—and any component using useSnapshot will automatically re-render.

Think of it like a broadcast tower: the state sits at the top, and anyone (components or plain functions) can reach up and change it. All subscribed listeners get the update instantly.

Using State in Non-Component Code

Import your Valtio state into any .js file:

// state.js
import { proxy } from 'valtio';

export const appState = proxy({
  notifications: [],
  theme: 'light'
});
// notificationService.js
import { appState } from './state';

export function addNotification(message) {
  appState.notifications.push({ id: Date.now(), message });
  // No hooks, no React—just mutate directly
}

// Called from a WebSocket, timer, or DOM event
setTimeout(() => addNotification('Background sync complete'), 5000);

Your React components automatically reflect the change because they're subscribed via useSnapshot.

Why This Matters

You're not locked into React's render cycle. Background tasks, third-party libraries, and async callbacks can all modify state directly. No need for dispatchers, contexts, or workarounds—just straightforward mutations that flow into your UI.

Key Takeaway: Valtio state is global JavaScript state first, React state second—mutate it from anywhere, and components stay in sync automatically through useSnapshot.