1.0.6 • Published 2 years ago
use-cross-tab-state v1.0.6
use-cross-tab-state
A React hook for state synchronization and persistence across multiple browser tabs. The broadcast-channel is used to dispatch state across tabs.
Installation
npm i use-cross-tab-state
# or
yarn add use-cross-tab-state
Usage
import { useCrossTabState } from 'use-cross-tab-state';
const App = () => {
const [counter, setCounter] = useCrossTabState('counter', 1);
return (
<button onClick={() => setCounter(counter + 1)}>
Click counter: {counter}
</button>
);
};
import { useCrossTabState } from 'use-cross-tab-state';
const App = () => {
const [news, setNews, { useLeader }] = useCrossTabState('news');
// useLeader is similar to useEffect: function will re-run when dependencies changed,
// except it will only run ONCE in the leader tab even if multiple tabs exist.
// See API reference for details
useLeader(() => {
console.log('[Leader] Fetching news...');
setNews(...);
}, []);
};
API Reference
useCrossTabState API
const [state, setState, results] = useCrossTabState(key, defaultValue, options);
Known Issues
- Broadcast channel does not work in Safari private tabs created manually. It works if the private tab is spawned by another private tab.
Credits
Special thanks to @kftsehk for constructive discussion!