How to use Broadcast Channel API for cross-tab communication in ReactJS

𝐔𝐬𝐢𝐧𝐠 𝐁𝐫𝐨𝐚𝐝𝐜𝐚𝐬𝐭 𝐂𝐡𝐚𝐧𝐧𝐞𝐥 𝐀𝐏𝐈 𝐢𝐧 𝐑𝐞𝐚𝐜𝐭 𝐉𝐒 𝐟𝐨𝐫 𝐂𝐫𝐨𝐬𝐬-𝐭𝐚𝐛 𝐜𝐨𝐦𝐦𝐮𝐧𝐢𝐜𝐚𝐭𝐢𝐨𝐧 If you need to sync state or user actions across multiple browser tabs, 𝐁𝐫𝐨𝐚𝐝𝐜𝐚𝐬𝐭 𝐂𝐡𝐚𝐧𝐧𝐞𝐥 API does it efficiently and without complex workarounds. 𝐄𝐱𝐚𝐦𝐩𝐥𝐞 𝐮𝐬𝐞 𝐜𝐚𝐬𝐞: A user logs out from one tab and you want all other open tabs to log out automatically. -------------------------------------------- // authChannel.js const channel = new BroadcastChannel('auth'); // Logout button click function export const sendLogout = () => channel.postMessage({ type: 'LOGOUT' }); export const listenLogout = (callback) => {  channel.onmessage = (event) => {   if (event.data.type === 'LOGOUT') callback();  }; }; useEffect(() => {  listenLogout(() => handleLogout()); }, []); -------------------------------------------- This automatically updates all open tabs in real time. No backend calls, no localStorage polling. The Broadcast Channel API is perfect for:  - Auth sync across tabs  - Multi-tab notifications  - Real-time preference or theme updates It’s a lightweight addition that makes your React apps feel more connected and responsive. Thanks to creators like Hitesh Choudhary, Akshay Saini 🚀, Piyush Agarwal, Web Dev Simplified and Codevolution for consistently sharing practical insights that help developers build smarter apps. #ReactJS #JavaScript #BroadcastChannel #WebDevelopment

  • text

To view or add a comment, sign in

Explore content categories