Animation Techniques in React Three Fiber

Published on September 15, 2024

Animation brings 3D scenes to life. Here’s a comprehensive look at animation techniques in React Three Fiber.

useFrame

The workhorse of R3F animation:

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

function SpinningBox() {
  const meshRef = useRef()
  
  useFrame((state, delta) => {
    meshRef.current.rotation.y += delta
  })
  
  return <mesh ref={meshRef}>...</mesh>
}

Spring Animation

For smooth, physics-based motion:

import { useSpring, animated } from '@react-spring/three'

function AnimatedBox() {
  const [springs, api] = useSpring(() => ({
    scale: 1,
    config: { mass: 1, tension: 170, friction: 26 }
  }))
  
  return (
    <animated.mesh 
      scale={springs.scale}
      onClick={() => api.start({ scale: 1.5 })}
    >
      ...
    </animated.mesh>
  )
}

Skeletal Animation

For character animation with bones:

import { useAnimations, useGLTF } from '@react-three/drei'

function Character() {
  const { scene, animations } = useGLTF('/character.glb')
  const { actions } = useAnimations(animations, scene)
  
  useEffect(() => {
    actions.walk?.play()
  }, [])
  
  return <primitive object={scene} />
}

Morph Targets

For facial animation and shape blending:

function Face() {
  const { scene } = useGLTF('/face.glb')
  
  useFrame(() => {
    const mesh = scene.getObjectByName('face')
    mesh.morphTargetInfluences[0] = Math.sin(Date.now() * 0.001)
  })
  
  return <primitive object={scene} />
}

Performance Tips

  • Use invalidate mode for non-continuous animation
  • Batch animations when possible
  • Consider GPU-based animation for particles
  • Profile animation code in useFrame
← Back to Articles