React
Learn how to create real-time, stateful React applications with Rivet's actor model. The React integration provides intuitive hooks for managing actor connections and real-time updates.
Basic Usage
Installation
Install the RivetKit React package:
Use in Components
Make sure you have a running Rivet actor server to connect to. You can follow the Node.js & Bun Quickstart to set up a simple actor server.
Connect to actors and listen for real-time updates:
API Reference
createRivetKit(client, options?)
Creates the Rivet hooks for React integration.
Parameters
client
: The Rivet client created withcreateClient
options
: Optional configuration object
Returns
An object containing:
useActor
: Hook for connecting to actors
useActor(options)
Hook that connects to an actor and manages the connection lifecycle.
Parameters
options
: Object containing:name
: The name of the actor type (string)key
: Array of strings identifying the specific actor instanceparams
: Optional parameters passed to the actor connectioncreateWithInput
: Optional input to pass to the actor on creationcreateInRegion
: Optional region to create the actor in if does not existenabled
: Optional boolean to conditionally enable/disable the connection (default: true)enabled
: Optional boolean to conditionally enable/disable the connection (default: true)
Returns
Actor object with the following properties:
connection
: The actor connection for calling actions, ornull
if not connectedisConnected
: Boolean indicating if the actor is connectedstate
: Current actor state (if available)useEvent(eventName, handler)
: Method to subscribe to actor events
actor.useEvent(eventName, handler)
Subscribe to events emitted by the actor.
Parameters
eventName
: The name of the event to listen for (string)handler
: Function called when the event is emitted
Lifecycle
The event subscription is automatically managed:
- Subscribes when the actor connects
- Cleans up when the component unmounts or actor disconnects
- Re-subscribes on reconnection
Advanced Patterns
Multiple Actors
Connect to multiple actors in a single component:
Conditional Connections
Control when actors connect using the enabled
option:
Real-time Collaboration
Build collaborative features with multiple event listeners:
Authentication
Connect authenticated actors in React:
Learn more about authentication.