0.2.0 • Published 4 years ago

react-broadcastchannel v0.2.0

Weekly downloads
3
License
MIT
Repository
-
Last release
4 years ago

react-broadcastchannel

GitHub Workflow Status npm bundle size npm

This library gives you a simple hook useBroadcastChannel to post or receive message from/to channels.

import * as React from 'react';
import { useBroadcastChannel } from 'react-broadcastchannel';

const App = () => {
  const [count, setCount] = React.useState(0);
  const [post] = useBroadcastChannel<number>('counter', ev => setCount(ev.data))

  const handler = () => {
    post(count + 1);
    setCount(count => count + 1);
  }

  return (
    <div>
      <button onClick={handler}>
        {count}
      </button>
    </div>
  );
};

What is BroadcastChannel API?

BroadcastChannel API allows to communicate between browsing contexts such as iframes, browser tabs, or even workers on the same origin.

API

useBroadcastChannel

const [post] = useBroadcastChannel<Message>('channel-id', event => event.data)