Search code examples
javascriptreactjsreact-hooksthree.jsreact-three-fiber

React Three useRef returns null in App direction for threejs objects


I am confused of using ref values while doing my threejs app in react. Normally, when we use useRef in any element, it returns exact object after first render. However, while working with threejs objects like mesh, perspective camera, it returns null after first render in app direction. I couldn't understand the problem behind that situation. Any ideas?

My idea is the ref might not immediately attach due to the way the 3D scene gets initialized. What do you think?

function App() {
  const cameraRef = useRef<THREE.PerspectiveCamera>(null);
  useEffect(() => {
    console.log(cameraRef.current);
  }, []);
  return (
    <div className="h-screen w-screen">
      <Canvas shadows>
        <PerspectiveCamera
          ref={cameraRef}
          makeDefault
          position={[0, 2, 3]}
          fov={75}
        />
      </Canvas>

Solution

  • This is discussed here.

    The maintainer states you should pass a setState function as ref and watch for state change.

    const [cam, set] = useState()
    useEffect(() => {
      if (cam) { ... }
    }, [cam])
    return (
      <Canvas>
        <PerspectiveCamera ref={set}>