Skip to main content

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 to useState:
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

  • Ensure all components use the same key parameter
  • Verify the ReactTogether provider wraps all components
  • Check that all users are in the same session
  • Increase throttleDelay in options
  • Use useMemo or useCallback for expensive computations
  • Consider breaking large state objects into smaller pieces
  • Check the resetOnDisconnect option
  • Ensure initial values are consistent across components
  • Verify the key string is exactly the same in all uses
  • Use appropriate throttling for frequently updated state
  • Avoid storing large objects or arrays in shared state
  • Consider using useStateTogetherWithPerUserValues for user-specific data

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!