React State Hook Bindings

Published Updated
Standard React hooks to bind component views to options, datasets, event channels, and Twin-Proxy stores.

React overlays observe state updates and patch adjustments back to the Vault. Rather than subscribing directly to the store, components must use these data-bound hooks to read and update Aircada configurations dynamically.

useAirStore React Hook#

React guidelines, 3-element tuple return signatures, and anti-spread rules for subscribing to and patching global reactive state.

Use the useAirStore hook to read application state configurations and patch values back to the global reactive Vault.

3-Element Tuple Return Signature

The useAirStore<T>() hook returns a 3-element tuple:

typescript
const [storeState, patchStore, setProperty] = useAirStore<AirStoreConfig>();
  • storeState: Read-only snapshot of the entire reactive state object.
  • patchStore(partialState): Merges partial objects into the state hierarchy.
  • setProperty(key, value): Convenience setter to mutate a single top-level key.

๐Ÿ›‘ Critical Anti-Patterns & Constraints

  1. Never Spread State in Patches: Do NOT spread existing state inside a patch (e.g. patchStore({ ...storeState, open: true }) or this.air.store.patch({ ...this.air.store.state, open: true })). The engine Vault performs atomic deep-partial diffing and automatically preserves all untouched fields. Spreading existing state creates stale closures and can overwrite concurrent updates from 3D operators.
  1. Never Destructure as an Object: Destructuring const { store } = useAirStore() fails TypeScript compilation because useAirStore returns a tuple array.
  1. Never Treat as useState: Calling useAirStore('activeStep', 1) assigns the entire store object to your variable and triggers React Error #31 (Objects are not valid as a React child).
  1. State Configuration Typing: Always provide the generic store config type parameter (e.g. useAirStore<AirStoreConfig>()) to ensure key autocompletion.
CartPanel.tsx (tsx)
import { useAirStore } from '@aircada/react';
import { AirStoreConfig } from './store/store.config';

export function CartPanel() {
    // 1. Signature: useAirStore returns [storeState, patchStore, setProperty]
    const [storeState, patchStore, setProperty] = useAirStore<AirStoreConfig>();

    const toggleCart = () => {
        // ๐ŸŸข CORRECT: Deep partial patch containing only the target key
        patchStore({ ui: { cartOpen: !storeState.ui.cartOpen } });
    };

    const handleSelectOption = (finishId: string) => {
        // ๐ŸŸข CORRECT: Single property setter
        setProperty('selectedFinish', finishId);
    };

    return (
        <div className="pointer-events-auto">
            <button onClick={toggleCart}>
                {storeState.ui.cartOpen ? 'Close Cart' : 'Open Cart'}
            </button>
            <button onClick={() => handleSelectOption('MATTE_BLACK')}>
                Set Matte Black
            </button>
        </div>
    );
}
Reading state, patching single properties, and multi-property deep merges using useAirStore

useAirOptions React Hook#

React guidelines and code examples for rendering and picking product options using useAirOptions.

The useAirOptions hook is the standard, data-bound hook for option selectors. It reads configuration selections, loads list details, and applies changes directly through Twin-Proxy paths.

Key Constraints

  1. Never Call useAirStore for Options: Do not manually subscribe or patch option models using low-level store hooks. Let useAirOptions manage it.
  1. Pass Option Set Object: Pass the entire optionSet object imported from the auto-generated OptionsRegistry.
ColorPicker.tsx (tsx)
import { useAirOptions } from '@aircada/react';
import { OptionsRegistry } from '../registry/options.generated';

export function ColorPicker() {
    // Bind to the option set object directly
    const { options, isLoading, activeSelection, selectOption } = useAirOptions(
        OptionsRegistry.BALL_O_STEEL.sets.SIMPLECOLORS
    );

    if (isLoading) return <div>Loading...</div>;

    return (
        <div className="flex gap-2 pointer-events-auto">
            {options.map(row => (
                <button
                    key={row.id}
                    className={activeSelection?.id === row.id ? 'border-cyan-500' : 'border-gray-500'}
                    onClick={() => selectOption(row)}
                >
                    {row.name}
                </button>
            ))}
        </div>
    );
}
Binding Option Selection to buttons with useAirOptions

useAirDataset React Hook#

React guidelines and code examples for fetching spreadsheet rows directly from Cloud Datasets.

Use the useAirDataset hook when a component only needs to fetch lists of items (e.g. menu contents, layout descriptors) and doesn't need active Option selection tracking.

Key Constraints

  1. Single Source of Truth: Never hardcode arrays or configurations that could live in a cloud spreadsheet. Maintain them in datasets.
  1. Strong Typing: Always pass the generic row type parameter to the hook. Import row interfaces directly from /registry/ files.
SidebarMenu.tsx (tsx)
import { useAirDataset } from '@aircada/react';
import { MediaRegistry, MenuDataRow } from '../registry/media.generated';

export function SidebarMenu() {
    // Strongly typed row fetching
    const { rows, isLoading } = useAirDataset<MenuDataRow>(
        MediaRegistry.DATASETS.MAIN_MENU.id
    );

    if (isLoading) return <div>Loading...</div>;

    return (
        <ul>
            {rows.map(row => (
                <li key={row.id}>{row.Label}</li>
            ))}
        </ul>
    );
}
Fetching and mapping cloud dataset rows in React

useAirEvent React Hook#

React guidelines, direct dispatcher function signatures, and code examples for broadcasting actions via the global event bus.

Use the useAirEvent hook to trigger transient, fire-and-forget commands (such as resetting camera states, triggering checkout animations, or notifying 3D systems) that do not belong in persistent option states.

Direct Callable Dispatcher Signature

The useAirEvent<TPayload>(eventName) hook accepts the event name string as its first argument and returns a direct callable dispatch function:

typescript

const emitEvent = useAirEvent<CartPayload>(EVENT_CART_ADD_REQUESTED);

emitEvent({ productId: 'ring-1', price: 499.00 });

Key Constraints

  1. Direct Invocation: Call emitEvent(payload) directly. Do NOT call emitEvent.invoke() or call useAirEvent() without arguments.
  1. Strict Payload Typing: Bind the event payload type parameter explicitly to ensure compile-time verification of dispatched parameters.
ActionButtons.tsx (tsx)
import { useAirEvent } from '@aircada/react';
import { Events, EventPayloads } from '../registry/registry.generated';

export function ActionButtons() {
    // Strongly typed event invocation returning direct dispatch function
    const emitResetCamera = useAirEvent<EventPayloads[typeof Events.RESET_CAMERA]>(
        Events.RESET_CAMERA
    );

    const handleReset = () => {
        emitResetCamera({ reason: 'User requested reset' });
    };

    return <button onClick={handleReset} className="pointer-events-auto">Reset Camera</button>;
}
Broadcasting strongly typed events in React using useAirEvent