trevoro / use-broadcast

React hook to sync state between browser tabs of the same origin
https://www.npmjs.com/package/use-broadcast
MIT License
15 stars 1 forks source link

📡 useBroadcast

This is a React hook that lets you keep two browser tabs / windows in sync. Behind the scenes it uses the Broadcast Channel API to send messages between instances. This way you can take action in one tab and have the state automatically shared with other instances of your component regardless of which window or tab they're in.

Demo

Example

import { useBroadcast } from 'use-broadcast';

export const MyComponent = () => {
  const initialState = 0;
  const [state, setState] = useBroadcast('channel_name', initialState);

  function click() {
    setState(state + 1);
  }

  return (
    <div>
      <button onClick={click}>increment</button>
    </div>
  )
}