This hook requires the OrderbookProvider to be present in your component tree to provide the underlying Orderbook instance.
Import
import { useOrderbookConnection } from '@krono/hooks'
Usage
import { useOrderbookConnection } from '@krono/hooks'
function ConnectionManager() {
const { status, connect, disconnect } = useOrderbookConnection();
return (
<div className="flex items-center gap-4">
<div className="flex items-center gap-2">
<StatusIndicator status={status} />
<span className="capitalize">{status}</span>
</div>
{status === 'closed' ? (
<button onClick={connect}>Connect</button>
) : (
<button onClick={disconnect}>Disconnect</button>
)}
</div>
);
}
Parameters
This hook does not accept any parameters. It automatically interfaces with the Orderbook instance provided by the nearest context provider.
Return Type
State
status
'connecting' | 'open' | 'closing' | 'closed'
The current state of the WebSocket connection.
Actions
Initiates a connection to the exchange WebSocket. If a connection is already in progress or open, this method usually performs no action.
Gracefully closes the active WebSocket connection and stops data processing.
Examples
Connection
Ensure a connection is active when a component mounts.
import { useEffect } from 'react';
import { useOrderbookConnection } from '@krono/hooks';
function TradingPanel() {
const { connect, disconnect, status } = useOrderbookConnection();
useEffect(() => {
connect();
return () => disconnect();
}, [connect, disconnect]);
if (status === 'connecting') return <p>Establishing link...</p>;
return <div>Active Trading UI</div>;
}
Reconnection Status UI
Because status is reactive, you can use it to drive complex UI states like loading spinners or error banners.
function ConnectionBadge() {
const { status } = useOrderbookConnection();
const colors = {
open: 'bg-green-500',
connecting: 'bg-yellow-500',
closing: 'bg-orange-500',
closed: 'bg-red-500',
};
return (
<span className={`px-2 py-1 rounded text-white ${colors[status]}`}>
{status}
</span>
);
}