File size: 14,282 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 |
---
meta:
title: React Three Fiber | React Spring
'og:title': React Three Fiber | React Spring
'twitter:title': React Three Fiber | React Spring
description: A detailed guide to using React Spring with React Three Fiber.
'og:description': A detailed guide to using React Spring with React Three Fiber.
'twitter:description': A detailed guide to using React Spring with React Three Fiber.
'og:url': https://www.react-spring.dev/docs/guides/react-three-fiber
'twitter:url': https://www.react-spring.dev/docs/guides/react-three-fiber
sidebar_position: 1
---
import { formatFrontmatterToRemixMeta } from '../helpers/meta'
export const meta = formatFrontmatterToRemixMeta(frontmatter)
# React Three Fiber
:::note
It's assumed you have a base understanding of `react-spring` and `react-three-fiber`. If you're new to
either, check out our [getting started](/docs/getting-started) or alternatively, the [react-three-fiber](https://docs.pmnd.rs/react-three-fiber) docs.
:::
## Introduction
In this guide we'll explore why `react-spring` is a valuable addition to your `react-three-fiber` project, working with the `imperative API`
to create performant animation updates on objects in the scene graph and with the [event system](/docs/advanced/events) of the library
to update parts of your scene that are not wrapped in our [`animated` HOC](/docs/concepts/animated-elements). To work with `react-spring`
and `react-three-fiber` you'll need to install the `@react-spring/three` package.
```bash
yarn add @react-spring/three @react-three/fiber three
```
## Why use the library?
A common question asked is why use `react-spring` with `react-three-fiber` when you can use the `useFrame` hook to update your meshes & objects
instead without knowing another API. Well this is a great question – its critical of motion design for animations to look realistic, and the beauty
of `react-spring` is the animations are physically correct.
When we consider that the animations you create with `react-spring` can not be interrupted per se, that is when you edit the value you don't have
the animation halt and start again, it responds to it's new goal value creating a seamless experience incredibly valuable to a 3D scene, you don't
see items in real life free fall and when an external force is applied they stall, they react accordingly. The dampening of a spring gives you the
additional feeling of real life physics whilst in combination of even the three most basic config parameter `mass`, `tension` and `friction` you can
create a wide range of animations that belong to different objects in your scenes, you might have a metal-like sphere that needs to move slowly compared
to your light translucent sphere that should be falling and bouncing around the scene.
Furthermore, the flexibility to start/stop and replay animations, particularly with state and device motion preferences, makes this a uniquely
accessible library from both a DX and UX perspective. Lets take a look at a simple use-case.
I have a distortion blob and I want to it to change color on click. You could do this with `useFrame` to perform frame by frame updates, `useRef`
to access the material object and use the `THREE.Color.lerp` function, slowly incrementing by the lerp value until the color is reached. But this then
requires that I keep track of a `THREE` instance of `Color` which _can_ lead to memory leaks if not handled correctly and not only that, but it would
be a lot of code. Then you'd need to think about writing your own easing functions. With `react-spring` you can do this in a few lines of code.
```tsx live=true template=r3f showLineNumbers lines=9,12,20 defaultOpen=true
import { useState } from 'react'
import { useSpring, animated } from '@react-spring/three'
import { MeshDistortMaterial } from '@react-three/drei'
import { Canvas } from '@react-three/fiber'
const AnimatedMeshDistortMaterial = animated(MeshDistortMaterial)
const MyScene = () => {
const [clicked, setClicked] = useState(false)
const springs = useSpring({
color: clicked ? '#569AFF' : '#ff6d6d',
})
const handleClick = () => setClicked(s => !s)
return (
<mesh onClick={handleClick}>
<sphereGeometry args={[1.5, 64, 32]} />
<AnimatedMeshDistortMaterial
speed={5}
distort={0.5}
color={springs.color}
/>
</mesh>
)
}
export default function MyComponent() {
return (
<Canvas>
<ambientLight intensity={0.8} />
<pointLight intensity={1} position={[0, 6, 0]} />
<MyScene />
</Canvas>
)
}
```
## Use the imperative API
The example above demonstrates the declarative approach to using `react-spring` hooks by passing a `config` object to the hook.
However, it can also receive a function argument instead, similar to react's `useEffect` hook.
In the example below, we use the power of the `react-spring`'s api to lean into the imperative requirements
of working with performant webGL scenes. The blob follows you round the canvas (lines 70-82) & scales on
interaction (lines 46-56) without a single react render to cause these updates.
In addition we use the provide a function to the `config` prop instead of an object to deliver a more sticky
config for the spring in general, but to give the blob a bouncy feel when the `scale` key is changed – lines 18-30.
Finally, because we're using the position of the mouse which can be considered a `Vector2` and the `position`
of a `mesh` is a `Vector3` we use a custom interpolation via the `to` method of a `SpringValue` to interpolate
the array, this can be seen on line 97 (also see [imperative API](/docs/concepts/imperative-api) and
[interpolation](/docs/advanced/interpolation)).
```tsx live=true template=r3f lines=18-30,46-56,70-82,97 showLineNumbers defaultOpen=true
import { useRef, useEffect, useCallback } from 'react'
import { useSpring, animated } from '@react-spring/three'
import { Canvas, useThree } from '@react-three/fiber'
import { MeshDistortMaterial } from '@react-three/drei'
const AnimatedMeshDistortMaterial = animated(MeshDistortMaterial)
const MyScene = () => {
const isOver = useRef(false)
const { width, height } = useThree(state => state.size)
const [springs, api] = useSpring(
() => ({
scale: 1,
position: [0, 0],
color: '#ff6d6d',
config: key => {
switch (key) {
case 'scale':
return {
mass: 4,
friction: 10,
}
case 'position':
return { mass: 4, friction: 220 }
default:
return {}
}
},
}),
[]
)
const handleClick = useCallback(() => {
let clicked = false
return () => {
clicked = !clicked
api.start({
color: clicked ? '#569AFF' : '#ff6d6d',
})
}
}, [])
const handlePointerEnter = () => {
api.start({
scale: 1.5,
})
}
const handlePointerLeave = () => {
api.start({
scale: 1,
})
}
const handleWindowPointerOver = useCallback(() => {
isOver.current = true
}, [])
const handleWindowPointerOut = useCallback(() => {
isOver.current = false
api.start({
position: [0, 0],
})
}, [])
const handlePointerMove = useCallback(
e => {
if (isOver.current) {
const x = (e.offsetX / width) * 2 - 1
const y = (e.offsetY / height) * -2 + 1
api.start({
position: [x * 5, y * 2],
})
}
},
[api, width, height]
)
useEffect(() => {
window.addEventListener('pointerover', handleWindowPointerOver)
window.addEventListener('pointerout', handleWindowPointerOut)
window.addEventListener('pointermove', handlePointerMove)
return () => {
window.removeEventListener('pointerover', handleWindowPointerOver)
window.removeEventListener('pointerout', handleWindowPointerOut)
window.removeEventListener('pointermove', handlePointerMove)
}
}, [handleWindowPointerOver, handleWindowPointerOut, handlePointerMove])
return (
<animated.mesh
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
onClick={handleClick()}
scale={springs.scale}
position={springs.position.to((x, y) => [x, y, 0])}
>
<sphereGeometry args={[1.5, 64, 32]} />
<AnimatedMeshDistortMaterial
speed={5}
distort={0.5}
color={springs.color}
/>
</animated.mesh>
)
}
export default function MyComponent() {
return (
<Canvas>
<ambientLight intensity={0.8} />
<pointLight intensity={1} position={[0, 6, 0]} />
<MyScene />
</Canvas>
)
}
```
## Syncing spring values
Sometimes, it's necessary to sync the state of a spring with an external source. This can be done with the [event system](/docs/advanced/events)
built into react-spring.
Take the following example, we have multiple blobs on our screen that start in different places and a component higher in our scene graph needs to to know
the position of each blob. Because the `position` is controlled by `useSpring` you can't simple submit `springs.position` to the store because you'll
be dispatching the whole `SpringValue` object, which is unnecessary and can weigh down your external store.
Instead, you can use the `onChange` event handler to `get` the value of your springs and react to them accordingly. The code below is a convoluted example
but demonstrates how you _could_ use the `onChange` event handler to sync a `THREE.Vector2` that is then returned when the parent component requires it via
`useImperativeHandle`.
```tsx live=true template=r3f defaultOpen=true showLineNumbers lines=11,20-22,40-42,114-125
import {
useRef,
useEffect,
useCallback,
forwardRef,
useState,
useImperativeHandle,
} from 'react'
import { useSpring, animated } from '@react-spring/three'
import { Canvas, useThree } from '@react-three/fiber'
import { MeshDistortMaterial } from '@react-three/drei'
import { Vector2 } from 'three'
const AnimatedMeshDistortMaterial = animated(MeshDistortMaterial)
const MyScene = forwardRef(({}, ref) => {
const isOver = useRef(false)
const [vector2] = useState(() => new Vector2())
const { width, height } = useThree(state => state.size)
const [springs, api] = useSpring(
() => ({
scale: 1,
position: [0, 0],
color: '#ff6d6d',
onChange: ({ value }) => {
vector2.set(value.position[0], value.position[1])
},
config: key => {
switch (key) {
case 'scale':
return {
mass: 4,
friction: 10,
}
case 'position':
return { mass: 4, friction: 220 }
default:
return {}
}
},
}),
[]
)
useImperativeHandle(ref, () => ({
getCurrentPosition: () => vector2,
}))
const handleClick = useCallback(() => {
let clicked = false
return () => {
clicked = !clicked
api.start({
color: clicked ? '#569AFF' : '#ff6d6d',
})
}
}, [])
const handlePointerEnter = () => {
api.start({
scale: 1.5,
})
}
const handlePointerLeave = () => {
api.start({
scale: 1,
})
}
const handleWindowPointerOver = useCallback(() => {
isOver.current = true
}, [])
const handleWindowPointerOut = useCallback(() => {
isOver.current = false
api.start({
position: [0, 0],
})
}, [])
const handlePointerMove = useCallback(
e => {
if (isOver.current) {
const x = (e.offsetX / width) * 2 - 1
const y = (e.offsetY / height) * -2 + 1
api.start({
position: [x * 5, y * 2],
})
}
},
[api, width, height]
)
useEffect(() => {
window.addEventListener('pointerover', handleWindowPointerOver)
window.addEventListener('pointerout', handleWindowPointerOut)
window.addEventListener('pointermove', handlePointerMove)
return () => {
window.removeEventListener('pointerover', handleWindowPointerOver)
window.removeEventListener('pointerout', handleWindowPointerOut)
window.removeEventListener('pointermove', handlePointerMove)
}
}, [handleWindowPointerOver, handleWindowPointerOut, handlePointerMove])
return (
<animated.mesh
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
onClick={handleClick()}
scale={springs.scale}
position={springs.position.to((x, y) => [x, y, 0])}
>
<sphereGeometry args={[1.5, 64, 32]} />
<AnimatedMeshDistortMaterial
speed={5}
distort={0.5}
color={springs.color}
/>
</animated.mesh>
)
})
export default function MyComponent() {
const blobApi = useRef(null)
useEffect(() => {
const interval = setInterval(() => {
if (blobApi.current) {
const { x, y } = blobApi.current.getCurrentPosition()
console.log('the blob is at position', { x, y })
}
}, 2000)
return () => clearInterval(interval)
}, [])
return (
<Canvas>
<ambientLight intensity={0.8} />
<pointLight intensity={1} position={[0, 6, 0]} />
<MyScene ref={blobApi} />
</Canvas>
)
}
```
## Troubleshooting
### Experiencing Jank?
Whilst jank in `react-three-fiber` cannot be purely blamed on `react-spring` you
might find toward the end of an animation that there's a subtle jump,
which is visible in [this demo](https://y18m1.csb.app/). It's not pretty, is it?
Whilst by default it would be nice to have this issue resolved without you having
to interact and this is something we'll consider for the next `breaking change`
in the meantime what you can use is the [`precision` config prop](/common/configs#configs) to avoid this.
```tsx
import { useSpring } from '@react-spring/three'
export default function MyComponent() {
const [springs, api] = useSpring(() => ({
position: [0, 0, 0],
config: {
precision: 0.0001,
},
}))
// ...
}
```
By setting the prop to a value like `0.0001` you can notice there is no jump towards 0.
This is because the precision prop is used to figure out how close the animated value
can get to the end goal before we consider the animated value to be equal to the end goal.
|