React Integration
The @pulse-js/react package provides a seamless integration with React, leveraging useSyncExternalStore for concurrent-mode safety.
Installation
Section titled “Installation”npm install @pulse-js/reactusePulse Hook
Section titled “usePulse Hook”This is the primary way to consume Pulse state.
With Sources
Section titled “With Sources”Returns the value and triggers re-render on change.
const count = source(0);
function Counter() { const value = usePulse(count); return <div>{value}</div>;}With Guards
Section titled “With Guards”Returns a GuardState object. In Pulse v3, the reason is always a structured object.
const isAdmin = guard(async () => { ... });
function AdminArea() { const { status, value, reason } = usePulse(isAdmin);
if (status === 'pending') return <Spinner />; if (status === 'fail') { return ( <div className="error"> <strong>{reason.code}</strong> <p>{reason.message}</p> </div> ); }
return <Dashboard data={value} />;}GuardReason Interface
Section titled “GuardReason Interface”The reason object contains the following properties:
code: A short string identifier (e.g.,'AUTH_REQUIRED').message: A human-readable description of the error.meta: Optional additional context.
Pulse reasons implement
toString(). You can render them directly in JSX:<p>{reason.toString()}</p>.
useGuard Hook
Section titled “useGuard Hook”A specialized hook for guards that supports React Suspense.
import { useGuard } from '@pulse-js/react';
function ProtectedContent() { const { status, value } = useGuard(authGuard, { suspend: true }); // If status is 'pending', this component will suspend return <div>{value}</div>;}PulseDevTools
Section titled “PulseDevTools”You can manually mount the DevTools if you don’t want to use the auto-injector.
import { PulseDevTools } from '@pulse-js/react/devtools';
function App() { return ( <> <Main /> <PulseDevTools shortcut="Ctrl+J" /> </> );}