Skip to content

React quickstart ​

Display public BTC REST and WebSocket prices from okx-api in a React component. No API key is needed. Prices are BTC-USDT last traded prices. This is a React browser app built with Vite; the plain JavaScript Vite guide uses DOM elements directly.

Use Node.js 24 and npm. You can also view the complete OKX React example on GitHub.

See Runtime compatibility for runtime requirements.

Keep the supplied Vite configuration: it resolves EventEmitter and rejects Node-only HTTPS agents. Browsers manage connections, so omit keepAlive. REST access depends on OKX CORS policy; use a server route if blocked. Keep credentials on your server.

Create the project ​

sh
mkdir okx-react-quickstart
cd okx-react-quickstart

1. Create package.json ​

Declare the SDK dependency and the commands used by this project.

json
{
  "name": "okx-react-quickstart",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite --host 127.0.0.1",
    "build": "vite build",
    "preview": "vite preview --host 127.0.0.1"
  },
  "dependencies": {
    "okx-api": "latest",
    "react": "19.2.0",
    "react-dom": "19.2.0",
    "events": "3.3.0"
  },
  "devDependencies": {
    "vite": "5.4.21",
    "@vitejs/plugin-react": "4.7.0"
  }
}

2. Install dependencies ​

Run this after saving package.json:

sh
npm install

3. Create sdk.vite.config.js ​

Resolve the SDK imports that need browser support. Keep this configuration when using the SDK in Vite.

js
import { fileURLToPath } from 'node:url';

const browserAgent = '\0okx-browser-agent';
const sdkRoot = fileURLToPath(new URL('./node_modules/okx-api/', import.meta.url));

export default {
  // Keep the same SDK transform during development and production builds.
  optimizeDeps: {
    exclude: ['okx-api'],
    include: ['events', 'okx-api > isomorphic-ws'],
  },
  resolve: {
    alias: {
      events: fileURLToPath(new URL('./node_modules/events/events.js', import.meta.url)),
    },
  },
  plugins: [{
    name: 'okx-browser-transport',
    enforce: 'pre',
    resolveId(source, importer) {
      if (source === 'https' && importer?.startsWith(sdkRoot)) {
        return browserAgent;
      }
    },
    load(id) {
      if (id === browserAgent) {
        // Browsers manage connections themselves. Reject an unsupported option
        // rather than presenting a Node Agent as a working browser transport.
        return `export class Agent {
  constructor() {
    throw new Error('keepAlive and HTTPS agents are Node.js-only. Omit keepAlive in a browser.');
  }
}`;
      }
    },
  }],
};

4. Create vite.config.js ​

Configure the development server and production build.

js
import { mergeConfig } from 'vite';
import react from '@vitejs/plugin-react';
import sdkConfig from './sdk.vite.config.js';

export default mergeConfig(sdkConfig, {
  plugins: [react()],
});

5. Create App.jsx ​

Build the React screen. The effect makes the REST request, subscribes to prices and closes the WebSocket on unmount.

jsx
import { useEffect, useState } from 'react';
import { RestClient, WebsocketClient } from 'okx-api';

function Prices() {
  const [restPrice, setRestPrice] = useState('Loading');
  const [livePrice, setLivePrice] = useState('Connecting');
  const [error, setError] = useState('');

  useEffect(() => {
    let mounted = true;
    const ws = new WebsocketClient();

    function showError(error) {
      console.error(error);
      if (mounted) {
        setError(error instanceof Error ? error.message : String(error));
      }
    }

    async function loadPrice() {
      const client = new RestClient();
      const tickers = await client.getTicker({ instId: 'BTC-USDT' });
      const price = tickers[0]?.last;

      if (!price) {
        throw new Error('No price was returned.');
      }

      if (mounted) {
        setRestPrice(String(price));
      }
    }

    loadPrice().catch(showError);

    const timeout = setTimeout(() => {
      showError(new Error('No BTC-USDT update within 30 seconds.'));
    }, 30_000);

    ws.on('update', (message) => {
      if (message.arg?.channel !== 'tickers') {
        console.log('WebSocket update:', message);
        return;
      }

      const price = message.data?.[0]?.last;

      if (mounted && price) {
        clearTimeout(timeout);
        setLivePrice(String(price));
      }
    });
    ws.on('exception', showError);

    // React can clean up an effect before its subscription starts.
    Promise.resolve().then(async () => {
      if (!mounted) {
        return;
      }

      try {
        await Promise.all(ws.subscribe({ channel: 'tickers', instId: 'BTC-USDT' }));
      } finally {
        // Close again if pending setup completed after unmount.
        if (!mounted) {
          ws.closeAll();
        }
      }
    }).catch(showError);

    return () => {
      mounted = false;
      clearTimeout(timeout);
      ws.closeAll();
    };
  }, []);

  return (
    <section>
      <p>BTC-USDT REST price: <output aria-label="REST price">{restPrice}</output></p>
      <p>BTC-USDT WebSocket price: <output aria-label="WebSocket price">{livePrice}</output></p>
      <p role="alert">{error}</p>
    </section>
  );
}

export default function App({ pageActive = true }) {
  const [running, setRunning] = useState(true);

  return (
    <main>
      <h1>BTC-USDT price</h1>
      {running && pageActive ? <Prices /> : <p>Stream stopped. WebSocket closed.</p>}
      <button type="button" onClick={() => setRunning(!running)}>
        {running ? 'Stop stream' : 'Start stream'}
      </button>
    </main>
  );
}

6. Create main.jsx ​

Mount the screen with StrictMode. Pause subscriptions while the browser caches the page, resume them on restoration and clean up when the page or entry module is discarded.

jsx
import { StrictMode } from 'react';
import { flushSync } from 'react-dom';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';

const root = createRoot(document.getElementById('root'));
let disposed = false;

function render(pageActive) {
  root.render(
    <StrictMode>
      <App pageActive={pageActive} />
    </StrictMode>,
  );
}

function dispose() {
  if (disposed) {
    return;
  }

  disposed = true;
  window.removeEventListener('pagehide', hide);
  window.removeEventListener('pageshow', show);
  root.unmount();
}

function hide(event) {
  if (event.persisted) {
    // Finish effect cleanup before the browser freezes this page.
    // Keep App mounted so its Stop/Start choice survives restoration.
    flushSync(() => render(false));
  } else {
    dispose();
  }
}

function show(event) {
  if (event.persisted && !disposed) {
    render(true);
  }
}

render(true);
window.addEventListener('pagehide', hide);
window.addEventListener('pageshow', show);

if (import.meta.hot) {
  import.meta.hot.dispose(dispose);
}

7. Create index.html ​

Create the browser page that loads the application entry module.

html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
    <title>React price screen</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/main.jsx"></script>
  </body>
</html>

Run ​

sh
npm run dev

Open Vite's printed URL, normally http://localhost:5173/. Both price fields should display positive numbers such as 65000.5. Tap Stop stream to unmount the price component and close its WebSocket. Start stream mounts a new component and creates a fresh subscription.

The effect ignores REST responses that arrive after unmount. Its cleanup closes the client before the effect runs again and when the component unmounts. This also handles StrictMode’s extra setup and cleanup cycle in development.

The entry module pauses the price component when the browser caches the page for Back or Forward navigation. Restoring the page resumes it without changing your Stop/Start choice. The module unmounts the React root when the page is discarded or Vite replaces the entry module. See React's effect lifecycle.

Build and preview the production app:

sh
npm run build
npm run preview

Troubleshooting ​

  • An events resolution error means the dependency or Vite config is missing. Copy the config exactly and restart Vite.
  • A brief extra connection in development is expected under StrictMode. If updates continue after Stop stream, check that the component cleanup closes the client and ignores late updates.
  • This example uses public market data only. Keep private keys and API credentials in a secure server-side environment, outside source files and browser bundles.
  • For network failures, inspect the browser's HTTPS and WSS requests to the exchange. Exchange CORS and regional restrictions apply. See Runtime compatibility for browser configuration and WebSocket subscriptions for subscription details.

Built by Siebly. Open source SDKs for exchange APIs.