The primary hook for accessing the MuJoCo simulation API from any component inside <MujocoCanvas>.
Narrow on isReady, isPending, or isError to get type-safe access to the API and refs.
Usage
import { useMujoco } from "mujoco-react";
function MyComponent() {
const sim = useMujoco();
if (sim.isPending) return <span>Loading...</span>;
if (sim.isError) return <span>Error: {sim.error}</span>;
// sim.api is fully typed here
return (
<button onClick={() => sim.api.reset()}>Reset</button>
);
}
Return Value
useMujoco() returns a UseMujocoResult with three variants:
Loading
{ status: "loading"; isPending: true; isReady: false; isError: false; error: null; api: null }
Error
{ status: "error"; isPending: false; isReady: false; isError: true; error: string; api: null }
Ready
{
status: "ready";
isPending: false;
isReady: true;
isError: false;
error: null;
api: MujocoSimAPI;
mjModelRef: RefObject<MujocoModel | null>;
mjDataRef: RefObject<MujocoData | null>;
}
The API Object
The api object (available when isReady is true) provides methods grouped into categories:
- Simulation Control —
reset(), setPaused(), setSpeed(), step(), getTime()
- State Management —
saveState(), restoreState(), setQpos(), applyKeyframe()
- Forces —
applyForce(), applyTorque(), setExternalForce()
- Model Introspection —
getBodies(), getJoints(), getSensors()
- Model Mutation —
setGravity(), setBodyMass(), setGeomFriction()
- Spatial Queries —
raycast(), project2DTo3D(), getCanvasSnapshot()
- Scene Management —
loadScene()
IK control is provided by the useIkController() hook — see useIkController and IK Control.
Camera animation is provided by the standalone useCameraAnimation() hook — see useCameraAnimation.
Direct Model/Data Access
For advanced use cases, access the raw MuJoCo model and data objects:
function AdvancedComponent() {
const sim = useMujoco();
useFrame(() => {
if (!sim.isReady) return;
const model = sim.mjModelRef.current;
const data = sim.mjDataRef.current;
if (!model || !data) return;
// Read raw WASM arrays
const nq = model.nq;
const qpos = data.qpos; // Float64Array
});
return null;
}
Direct model/data access bypasses the API’s safety checks. Be careful with array indexing and avoid writing to arrays that the provider manages (e.g., qfrc_applied is zeroed each frame).
Notes
- Must be called from a component inside
<MujocoCanvas> or <MujocoPhysics>
- The
api object is stable (same reference across renders when status doesn’t change)
- Use
isReady / isPending / isError for type-safe narrowing instead of comparing status strings