<Canvas /> and the render loop

Back to Modules

<Canvas /> and the Render Loop in React Three Fiber

In React Three Fiber (R3F), the <Canvas> component is the cornerstone of your 3D scene. It acts as the entry point and a portal into Three.js, rendering Three.js elements rather than standard DOM elements. It also plays a crucial role in managing the render loop, abstracting away much of the underlying Three.js setup.

The <Canvas> Component

When you use the <Canvas> component, R3F automatically sets up several essential elements for your 3D scene:

The <Canvas> component stretches to 100% of its parent container, so you need to ensure its parent has defined dimensions for the canvas to be visible.

The React Three Fiber Render Loop

In traditional Three.js, you would typically set up your own animation loop using requestAnimationFrame. R3F abstracts this away, providing an automatic render loop by default.

Example: Basic R3F Canvas and Render Loop

This is a conceptual example showing how a basic R3F setup looks. Note that this requires a React environment to run.

import React, { useRef } from 'react';
import { Canvas, useFrame } from '@react-three/fiber';

function Box(props) {
  const meshRef = useRef();
  useFrame(() => {
    if (meshRef.current) {
      meshRef.current.rotation.x += 0.01;
      meshRef.current.rotation.y += 0.01;
    }
  });

  return (
    <mesh {...props} ref={meshRef}>
      <boxGeometry args={[1, 1, 1]} />
      <meshStandardMaterial color={'orange'} />
    </mesh>
  );
}

export default function App() {
  return (
    <Canvas>
      <ambientLight />
      <pointLight position={[10, 10, 10]} />
      <Box position={[-1.2, 0, 0]} />
      <Box position={[1.2, 0, 0]} />
    </Canvas>
  );
}