The useRive Hook

The useRive hook is the foundation of the rive-react library and provides the most power and flexibility for integrating Rive animations.

While the <Rive /> component is great for simple playback, useRive gives you direct access to the Rive instance, allowing for advanced interactivity, event handling, and dynamic control.

Basic Usage

The useRive hook takes the same parameters as the <Rive /> component and returns an object containing the RiveComponent to render and the rive instance itself.

import { useRive } from '@rive-app/react-canvas';

const MyAnimation = () => {
  const { RiveComponent, rive } = useRive({
    src: 'skills.riv',
    stateMachines: 'Designer Skills',
    autoplay: true,
  });

  return <RiveComponent />;
};

Return Value (RiveState)

The hook returns an object with the following properties:

  • RiveComponent: A React component that you must render. It creates the <div> wrapper and <canvas> element needed for the animation. It accepts standard props like style and className.
  • rive: The Rive instance from the core runtime, or null if it hasn't loaded yet. This object is your gateway to the full Rive API.
  • setCanvasRef: A ref callback to be passed to your canvas element if you choose to render it manually.
  • setContainerRef: A ref callback for the canvas's parent container, used for automatic resizing.
  • canvas: The raw canvas DOM element.
  • container: The raw container DOM element.

Why use useRive?

You should use the useRive hook whenever you need to go beyond simple "play and forget" animations. The rive instance allows you to:

  • Control State Machine Inputs: Get and set inputs on your state machines to react to user interaction or application state changes. See the State Machines Guide.
  • Listen to Rive Events: Subscribe to events dispatched from your state machine to trigger actions in your React code. See the Events Guide.
  • Manually Control Playback: Call methods like rive.play(), rive.pause(), rive.stop(), and rive.reset() dynamically.
  • Access Rive Properties: Inspect artboards, animations, and other properties of your loaded Rive file.

Example: Pausing an animation on button click

import { useRive } from '@rive-app/react-canvas';

const ControllableAnimation = () => {
  const { RiveComponent, rive } = useRive({
    src: 'truck.riv',
    animations: 'idle',
    autoplay: true,
  });

  const handlePause = () => {
    if (rive) {
      rive.pause();
    }
  };

  return (
    <div>
      <RiveComponent style={{ height: '400px' }} />
      <button onClick={handlePause}>Pause</button>
    </div>
  );
};

In this example, we get the rive instance and use it to call the pause() method when a button is clicked. This level of control is only possible with the useRive hook.