Adding Liveblocks to existing useState hooks

You can easily add Liveblocks to an existing useState hook by broadcasting and listening to events.

import { useState } from "react";import { useBroadcastEvent, useEventListener } from "./liveblocks.config";
function useCustomState() { const [state, setState] = useState(); const broadcast = useBroadcastEvent();
// Update useState and broadcast an event const setStateAndBroadcast = (newValue) => { setState(newValue); broadcast({ type: "STATE_UPDATE", data: newValue }); };
// Listen for the broadcast event useEventListener(({ event }) => { if (event.type === "STATE_UPDATE") { setState(event.data); } });
return [state, setStateAndBroadcast];}