javascript / expert
Snippet
Cross-Tab State Synchronization with BroadcastChannel
This hook facilitates real-time state synchronization across multiple browser tabs of the same origin without using storage events. It leverages the BroadcastChannel API for low-latency communication.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function useTabSync(key, initialState) {const [state, setState] = useState(initialState);const channel = useRef(new BroadcastChannel(`sync_${key}`));useEffect(() => {const bc = channel.current;bc.onmessage = (event) => {setState(event.data);};return () => bc.close();}, []);const setSyncedState = (newValue) => {setState(newValue);channel.current.postMessage(newValue);};return [state, setSyncedState];}
react
Breakdown
1
new BroadcastChannel(`sync_${key}`)
Initializes a dedicated communication pipe for a specific state key.
2
bc.onmessage = (event) => { setState(event.data); }
Listens for updates from other tabs and updates the local state accordingly.
3
channel.current.postMessage(newValue)
Broadcasts the new state value to all other active instances of the channel.