Search code examples
reactjstypescriptreact-three-fiber

React-three-fiber hooks can only be used within the Canvas component


I have these two components:

Camera.tsx

import { useGLTF } from "@react-three/drei"


export default function Camera() {
  const gltf = useGLTF('/scene.gltf', true)
  return (
    <primitive object={gltf.scene} dispose={null}/>
  )
}

And using it in Landing.tsx

import { Suspense, useRef } from 'react';
import { Canvas, useFrame } from 'react-three-fiber';
import { Html } from '@react-three/drei';
import Camera from '../components/Camera';
import Lights from '../components/Lights';

export default function Landing() {
    const mesh = useRef();
     useFrame(() => {
    (mesh.current as any).rotation.x  += 0.01
  })
    return (
        <div className='Landing'>
            <Canvas colorManagement camera={{ position: [0, 0, 250], fov: 70 }}>
                <Suspense fallback={null}>
                <Lights />
                    <mesh ref={mesh} position={[-6, 75, 0]}>
                        <Camera />
                    </mesh>
                    <Html fullscreen>
                        <div className='Landing-container'>
                            <h1 className='Landing-header'>WELCOME</h1>
                        </div>
                    </Html>
                </Suspense>
            </Canvas>
        </div>
    );
}

Everything works just fine, the image loads... until I use the useFrame hook - then I get an error - React-three-fiber hooks can only be used within the Canvas component! I'm a little confused as the ref is a child of the Canvas component


Solution

  • useFrame needs the Canvas context in order to work. You need to call useFrame hook inside some component placed as descendant of Canvas. Something like this:

    const MyMesh = () => {
      const refMesh = useRef();
    
      useFrame(() => {
        if(refMesh.current) {
          // rotating the object
          refMesh.current.rotation.x += 0.01;
        }
      });
      return (<mesh ref={refMesh} />);
    }
    
    export default () => (
      <Canvas>
        <MyMesh />
      </Canvas>
    
    )