Skip to content

useFrame

Import

import { useFrame } from '@react-three/fiber'

Video Lecture

Section Video Links
useFrame Hook useFrame Hook useFrame Hook

Description

The useFrame hook is a React Three Fiber hook, and is useful if you want to execute code before every rendered frame.

In this example we will transform the mesh's rotation.

When React calls our useFrame hook, it gives us a state object of the Three.js scene, and a clock delta indicating how many milliseconds since the last time the delta was set. The delta time shows the milliseconds between renders and can be used to change an object over time at a consistent speed independent of the clients frame rate.

E.g., you could move an object at a speed of 10 units per second.

ref.current.position.x += 10 * delta

The useFrame hook will be invoked after the JSX is converted into Three.js objects and just before the current frame is rendered to the canvas.

The useFrame hook is invoked continually, and on desktop, will try to maintain a rate of 60 frames per second.

./src/Box.jsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import { useRef } from 'react'
import { useFrame } from '@react-three/fiber'

export default function Box(props) {
  const ref = useRef()

  useFrame((_, delta) => {
    ref.current.rotation.x += 1 * delta
    ref.current.rotation.y += 0.5 * delta
  })

  return (
    <mesh {...props} ref={ref}>
      <boxGeometry />
      <meshBasicMaterial color={0x00ff00} wireframe />
    </mesh>
  )
}

Working Example

<>
useFrame docs.pmnd.rs sbedit.net
THREE.Clock threejs.org
THREE.Object3D threejs.org sbcode.net

GitHub Branch

git clone https://github.com/Sean-Bradley/React-Three-Fiber-Boilerplate.git
cd React-Three-Fiber-Boilerplate
git checkout useFrame
npm install
npm start

Comments