use-user-channel.ts 401 B

123456789101112131415
  1. import { useEffect, useRef } from 'react'
  2. export const useUserChannel = (): BroadcastChannel | null => {
  3. const channelRef = useRef<BroadcastChannel | null>(null)
  4. if (channelRef.current === null && 'BroadcastChannel' in window) {
  5. channelRef.current = new BroadcastChannel('user')
  6. }
  7. useEffect(() => {
  8. return () => channelRef.current?.close?.()
  9. }, [])
  10. return channelRef.current
  11. }