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];}

We use cookies to collect data to improve your experience on our site. Read our Privacy Policy to learn more.