notque/vexjoy-agent / skills/game/game-dev
game-dev
FlaggedGame development: design, asset pipelines, Phaser, Unity CLI and builds, vanilla JS frontend, GM mode, match booking.
references/rive-skeletal-animator/rive-async-patterns.md
View on GitHub# Rive Async Patterns Reference
> **Scope**: Async instance lifecycle, null-guarding `rive`, loading states, event callback sequencing.
> **Version range**: `@rive-app/react-canvas` 4.x, React 18/19
> **Generated**: 2026-04-14
---
`useRive` returns null `rive` until `.riv` loads and WASM initializes. This async gap is the most common runtime error source — firing inputs before ready silently fails or throws. Guard: state machine input access, manual playback, and Zustand bridging.
## Pattern Table
| Pattern | Use When | Avoid When |
|---------|----------|------------|
| `if (!rive) return` guard in `useEffect` | accessing rive in effects | synchronous render path |
| `onLoad` callback | one-time post-load setup | polling rive for non-null |
| `onStateChange` for animation complete | waiting for animation finish | setTimeout sequencing |
| `isLoading` from `useRive` | showing loading placeholder | — (always show feedback) |
---
## Correct Patterns
### Null-Guarding the Rive Instance in Effects
```tsx
const { rive, RiveComponent } = useRive({
src: '/assets/characters/player.riv',
stateMachines: 'CombatStateMachine',
autoplay: true,
});
useEffect(() => {
if (!rive) return;
const attackInput = rive
.stateMachineInputs('CombatStateMachine')
?.find(i => i.name === 'triggerAttack');
attackInput?.fire();
}, [rive, triggerAttack]);
```
`rive` transitions null → instance once. Listing it as dependency ensures the effect fires at the exact moment it's ready.
---
### Using onLoad for One-Time Post-Load Setup
```tsx
const inputsRef = useRef<Record<string, StateMachineInput>>({});
const { rive, RiveComponent } = useRive({
src: '/assets/characters/player.riv',
stateMachines: 'CombatStateMachine',
autoplay: true,
onLoad: () => {
const inputs = rive!.stateMachineInputs('CombatStateMachine') ?? [];
inputs.forEach(input => { inputsRef.current[input.name] = input; });
},
});
```
`onLoad` fires once after the Rive runtime signals artboard ready.
---
### Detecting Animation Completion via onStateChange
Do not use `setTimeout`. Use `onStateChange`:
```tsx
const { rive, RiveComponent } = useRive({
src: '/assets/characters/player.riv',
stateMachines: 'CombatStateMachine',
autoplay: true,
onStateChange: (event: StateChangeEvent) => {
if (event.data.includes('idle')) {
dispatch({ type: 'ANIMATION_COMPLETE' });
}
},
});
```
`onStateChange` is driven by Rive's internal clock, stays in sync regardless of frame rate.
---
### Bridging Rive Inputs to Zustand Store
Store a callback, not the Rive instance, in Zustand:
```tsx
const { rive, RiveComponent } = useRive({ ... });
useEffect(() => {
if (!rive) return;
useCombatStore.getState().registerFireInput(
(inputName: string) => {
const inputs = rive.stateMachineInputs('CombatStateMachine');
inputs?.find(i => i.name === inputName)?.fire();
}
);
return () => useCombatStore.getState().registerFireInput(null);
}, [rive]);
```
A callback defers instance lookup to call time, avoiding stale references.
---
## Pattern Catalog
### Guard Rive Instance Access in Effects
**Detection**:
```bash
grep -rn 'rive\.' --include="*.tsx" | grep -v 'useEffect\|onLoad\|onStateChange\|useCallback\|//' | grep -v 'RiveComponent\|useRive\|import'
```
**Signal**: `rive.stateMachineInputs(...)` outside a guarded effect — `rive` is null on first render, throws `TypeError`.
**Fix**: Move to `useEffect` with `[rive]` dependency and `if (!rive) return` guard.
---
### Use onStateChange for Animation Sequencing
**Detection**:
```bash
grep -rn 'setTimeout' --include="*.tsx" | grep -i 'anim\|rive\|attack\|hit\|state'
```
**Signal**: `setTimeout(() => { recoverInput?.fire(); }, 300)` — duration drifts from actual animation at non-60fps.
**Fix**: Use `onStateChange` to detect state transitions. In `@rive-app/react-canvas` 4.x, `event.data` is `string[]` of current state names.
---
### Use Effect Dependencies Instead of Polling
**Detection**:
```bash
grep -rn 'setInterval\|while.*rive\|poll' --include="*.tsx" | grep -i 'rive'
```
**Signal**: `setInterval` polling for `rive !== null`. Reimplements what `useRive` already does with `onLoad`.
**Fix**: Use `useEffect([rive])` or `onLoad` callback.
---
## Error-Fix Mappings
| Error | Root Cause | Fix |
|-------|------------|-----|
| `TypeError: Cannot read properties of null (reading 'stateMachineInputs')` | `rive` accessed before load | `if (!rive) return` guard; `useEffect([rive])` |
| `useStateMachineInput returns null` | Input name typo or state machine name mismatch | Check Rive Editor for exact case-sensitive names |
| Animation fires once then stops | `autoplay: true` with one-shot, no loop | Use state machine with looping idle |
| `onStateChange` not firing | State machine name mismatch | Check `stateMachines:` param spelling |
| Inputs fire, no visual change | Wrong artboard selected | Add `artboard: 'ArtboardName'` param |
---
## Detection Commands
```bash
# Direct rive access outside effect/callback (null dereference risk)
grep -rn 'rive\.' --include="*.tsx" | grep -v 'useEffect\|onLoad\|onStateChange\|useCallback\|//'
# setTimeout animation sequencing (timing drift)
grep -rn 'setTimeout' --include="*.tsx" | grep -i 'anim\|attack\|hit\|fire\|input'
# Polling for rive instance
rg 'setInterval' --type tsx -l | xargs grep -l 'rive'
# Missing null guard in effects
grep -rn 'useEffect' --include="*.tsx" -A5 | grep -v 'if.*rive\|!rive' | grep 'rive\.'
```
---
## See Also
- `rive-react-setup.md` — Full `useRive` parameter reference
- `rive-performance.md` — WebGL cleanup, lazy loading, canvas sizing
- `rive-animation-library.md` — State machine design, `onStateChange` states
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deployment | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy. | Stars: 119k | Updated | Claude CodeCodex | Verified | Install |
| childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |