Overview
useStateTogether is the core hook of React Together. It creates state that is automatically synchronized across all users in your session. It works exactly like React’s useState, but any state changes are instantly shared with all connected users.
Perfect for: Shared counters, form data, game state, collaborative editing, or any state that should be the same for all users.
Basic Usage
Signature
Parameters
string
required
Unique identifier for this shared state. All users with the same key will share the same state.
T
required
Initial value when the state is first created. This only applies when no user has set this state yet.
UseStateTogetherOptions
Configuration options for the shared state behavior
Options
boolean
default:"false"
Whether to reset to initial value when all users disconnect
number
default:"100"
Milliseconds to throttle state updates (prevents excessive network traffic)
Return Value
Returns a tuple identical touseState:
T
The current state value, synchronized across all users
Dispatch<SetStateAction<T>>
Function to update the state. Accepts new value or updater function.
Examples
Simple Counter
Shared Text Input
Complex Object State
Array State Management
Advanced Usage
With Custom Options
Multiple Shared States
Functional Updates
Best Practices
Use Unique Keys
Choose descriptive, unique keys for each shared state
Use Functional Updates
Always use functional updates for complex state
Consider Performance
Use throttling for frequently updated state
Initialize Properly
Provide sensible initial values
Common Patterns
Reset Functionality
Conditional Updates
TypeScript Support
useStateTogether is fully typed and provides excellent TypeScript support:
Troubleshooting
State not synchronizing
State not synchronizing
- Ensure all components use the same
keyparameter - Verify the
ReactTogetherprovider wraps all components - Check that all users are in the same session
Frequent re-renders
Frequent re-renders
- Increase
throttleDelayin options - Use
useMemooruseCallbackfor expensive computations - Consider breaking large state objects into smaller pieces
State resets unexpectedly
State resets unexpectedly
- Check the
resetOnDisconnectoption - Ensure initial values are consistent across components
- Verify the key string is exactly the same in all uses
Performance issues
Performance issues
- Use appropriate throttling for frequently updated state
- Avoid storing large objects or arrays in shared state
- Consider using
useStateTogetherWithPerUserValuesfor user-specific data
Related Hooks
useStateTogetherWithPerUserValues
For state that varies per user while staying synchronized
useConnectedUsers
Get information about all connected users
useFunctionTogether
Execute functions synchronously across all users
useChat
Add real-time chat functionality
useStateTogether is the foundation of React Together. Once you understand how it works, you can build any kind of collaborative feature by combining it with other hooks and components!