# React

> Add controller support to a React game or app with @gamepadly/sdk. Share one hub through a provider that survives StrictMode, run the game loop in an effect without re-rendering every frame, show button prompts for the player's controller, and render on the server safely.

Source: https://gamepadly.com/sdk/recipes/react

In React, the SDK lives in effects: create the hub once for the whole app, run the game loop inside an effect, and
re-render only when something the UI shows changes, such as which controller is connected. This page builds those
three pieces. The code uses only hooks and `createRoot`, so it needs React 18 or later.

```bash
npm install @gamepadly/sdk
```

## 1. One hub for the app

```tsx
'use client'; // Next.js App Router: the provider uses hooks. Other setups ignore this line.

import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
import { createGamepadly, type GamepadlyHub } from '@gamepadly/sdk';

const GamepadlyContext = createContext<GamepadlyHub | null>(null);

export function GamepadlyProvider({ children }: { children: ReactNode }) {
  const [hub, setHub] = useState<GamepadlyHub | null>(null);
  useEffect(() => {
    const created = createGamepadly();
    setHub(created);
    return () => created.dispose(); // stops rumble and resets triggers
  }, []);
  return <GamepadlyContext.Provider value={hub}>{children}</GamepadlyContext.Provider>;
}

/** The app's hub, or null until the provider's effect has run. */
export function useGamepadly(): GamepadlyHub | null {
  return useContext(GamepadlyContext);
}
```

Wrap the app once, near the root:

```tsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { GamepadlyProvider } from './gamepadly';
import { Game } from './Game';

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <GamepadlyProvider>
      <Game />
    </GamepadlyProvider>
  </StrictMode>,
);
```

Why an effect and not `useMemo` or a module-level `createGamepadly()`:

- **StrictMode** mounts every effect twice in development: effect, cleanup, effect. The cleanup disposes the first
  hub and the second effect creates a fresh one, so exactly one hub is live. A hub created during render is never
  disposed.
- **Server rendering** (Next.js, Remix, Astro islands) never runs effects, so nothing touches `navigator` on the
  server. Until the effect runs, `useGamepadly()` returns `null`.
- **One hub per page.** Put the provider above everything that uses a controller, not inside a component that mounts
  and unmounts.

## 2. The game loop in an effect

Keep game state in the effect, not in React state. Calling `setState` 60 times a second re-renders the tree every
frame; drawing to a canvas from the loop does not render at all.

```tsx
import { useEffect, useRef } from 'react';
import { useGamepadly } from './gamepadly';

export function Game() {
  const hub = useGamepadly();
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!hub || !canvas) return;
    const ctx = canvas.getContext('2d')!;
    const p1 = hub.player(0);
    const actions = p1.createActions({
      actions: { fire: ['south', 'r2', 'Space'] },
      axes: { moveX: { stick: 'lx', negativeButtons: ['left'], positiveButtons: ['right'], negativeKeys: ['ArrowLeft'], positiveKeys: ['ArrowRight'] } },
    });
    const ship = { x: 300 };

    let frame = requestAnimationFrame(function tick(now) {
      actions.update(p1.input.getState(), now); // once per frame, before reading actions
      ship.x = Math.max(20, Math.min(580, ship.x + actions.axis('moveX') * 6));
      if (actions.justPressed('fire')) p1.haptics.playPreset('recoil', { pan: ship.x / 300 - 1 });

      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.fillStyle = '#0a84ff';
      ctx.fillRect(ship.x - 20, 250, 40, 20);
      frame = requestAnimationFrame(tick);
    });

    return () => {
      cancelAnimationFrame(frame);
      actions.dispose(); // removes its keyboard listeners
    };
  }, [hub]);

  return <canvas ref={canvasRef} width={600} height={300} />;
}
```

The effect depends on `hub`, so it starts once the provider has created it and restarts cleanly in StrictMode.

## 3. Prompts for the player's controller

The UI should say "Press A" to an Xbox player and "Press Cross" to a PlayStation player, and ask for a button press
until the browser reports a controller (browsers hide controllers until one is pressed). That information changes
rarely, so it is the one thing worth putting in React state:

```tsx
import { useEffect, useState } from 'react';
import { getButtonLabel, type ControllerBrand } from '@gamepadly/sdk';
import { useGamepadly } from './gamepadly';

export function useController() {
  const hub = useGamepadly();
  const [controller, setController] = useState<{ connected: boolean; brand: ControllerBrand }>({ connected: false, brand: 'generic' });

  useEffect(() => {
    if (!hub) return;
    const read = () => {
      const caps = hub.active.getCapabilities();
      setController({ connected: caps.tier !== 'keyboard_mouse', brand: caps.identity.brand });
    };
    read();
    return hub.onCapabilitiesChange(read); // returns the unsubscribe function
  }, [hub]);

  return controller;
}

export function FireHint() {
  const { connected, brand } = useController();
  return <p>{connected ? `${getButtonLabel('south', brand)} to fire` : 'Press any button on your controller'}</p>;
}
```

DualSense adaptive triggers and Switch Pro HD Rumble need one WebHID permission, which the browser only asks for
from a click:

```tsx
import { useGamepadly } from './gamepadly';

export function ConnectButton() {
  const hub = useGamepadly();
  if (!hub || !('hid' in navigator)) return null;
  return <button onClick={() => void hub.connectWebHID()}>Connect controller (WebHID)</button>;
}
```

## React Three Fiber

The provider works the same. Create the actions in a `useEffect` as above, keep them in a ref, and call
`actions.update()` at the top of `useFrame`. The [Three.js](https://gamepadly.com/sdk/recipes/three-js) recipe shows camera-relative
movement and panning haptics to a position on screen.

## Next steps

- [Start a new game](https://gamepadly.com/sdk/start/quick-start) covers adaptive triggers and a test that runs without a controller.
- [Buttons and layouts](https://gamepadly.com/sdk/guides/buttons-and-layouts) lists every button name and label.
- [Multiple players](https://gamepadly.com/sdk/guides/multiplayer) covers `hub.player(1)` and up for local co-op.
