shadimage
Hookagain
hookuse-phoenix-channelsource: ok · refreshed

Use Phoenix Channel

npx shadcn add "https://hookagain.vercel.app/r/use-phoenix-channel.json"
free

No selection tags yet — empty means no evidence, not lack of support.

Dependencies

Bundle weight · light
phoenix

Files1 · source cached 10/2/2026, 4:10:13 PM

hooks/use-phoenix-channel.ts
import type { Channel, Socket } from "phoenix";
import { useEffect, useState } from "react";

export function usePhoenixChannel(
	socket: Socket | null,
	topic: string,
	payload?: Record<string, unknown>,
	callbacks?: Record<string, (payload: any) => void>,
) {
	const [channel, setChannel] = useState<Channel | null>(null);

	useEffect(() => {
		if (!socket) return;

		const phoenixChannel = socket.channel(topic, {
			payload,
		});

		if (callbacks) {
			// register callbacks
			Object.entries(callbacks).forEach(([event, callback]) => {
				phoenixChannel.on(event, callback);
			});
		}

		phoenixChannel.join().receive("ok", () => {
			setChannel(phoenixChannel);
		});

		return () => {
			phoenixChannel.leave();
		};
	}, [socket, topic]);

	return channel;
}

More from Hookagain

Browse all components in this library →