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

2

8

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

Wanda answered 4/1, 2021 at 8:7 Comment(1)
you are using useFrame outside the canvas, but it depends on the canvases context. make the rotating mesh a self-contained component and the error will go away.Kreiker
R
24

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>

)
Rivi answered 21/4, 2021 at 17:30 Comment(0)
S
3

I had the same issue because of unintentionally mixing namespaces while trying to upgrade.. I was using react-three-fiber instead of @react-three/fiber.

Sideways answered 30/10, 2022 at 14:32 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.