useFunctionTogether hook allows all users to execute the same function simultaneously with the same arguments. When any user calls the synchronized function, all users that are rendering this hook with the same rtKey will execute their local version of the function at the same time.
Only the function arguments are guaranteed to be the same across every user. If the function captures local variables, those may differ between users. For perfectly synchronized state with stronger guarantees, consider using the underlying @multisynq/react library.
Basic Usage
Signature
Parameters
string
required
The key used to identify this function across all users in the session.
T extends (...args: any[]) => any
required
The function to be synchronized. This function will be executed by all users when any user calls the returned synchronized function.
Return Value
T
The synchronized function. When called, it will execute the original function on all users with the same arguments.
Examples
Meditation Bell
Create a meditation bell that rings for all participants simultaneously:Collaborative Animations
Synchronize animations across all users for presentations or demos:Game State Synchronization
Synchronize game events like starting rounds or triggering special effects:Synchronized Notifications
Create a notification system that shows messages to all users:Best Practices
Function Design
- Keep functions side-effect focused - Ideal for UI updates, animations, and notifications
- Use useCallback for optimization - Wrap functions in
useCallbackto prevent unnecessary re-synchronizations - Handle failures gracefully - Always account for functions that might fail (like audio playback)
State Management
- Combine with state hooks - Use alongside
useStateTogetherfor state updates triggered by functions - Avoid heavy computations - Functions should be fast since they run on all users
- Consider network latency - Some delay between users is normal
User Experience
- Provide visual feedback - Show when functions are executing or have completed
- Disable during execution - Prevent spam-clicking that could overwhelm users
- Clear naming - Use descriptive
rtKeynames that indicate the functionโs purpose
Performance
- Debounce rapid calls - For frequently called functions, consider local debouncing
- Minimal dependencies - Keep function dependencies to a minimum to avoid re-creation
- Error boundaries - Wrap components using synchronized functions in error boundaries
Common Patterns
Event Broadcasting
Perfect for announcing events that all users should know about:Synchronized Media Control
Control media playback across all users:Collaborative Actions
Trigger actions that affect shared collaborative spaces:Related Hooks
useStateTogether- For synchronized state managementuseStateTogetherWithPerUserValues- For per-user state trackinguseConnectedUsers- Get information about connected users