Threejs to R3F

2023-03-05.txt

I rewrote a colordrop effect that I made last week using R3F (React Three Fiber). The goal was to find out the complexity of creating a colordrop effect using R3F — and to get an initial understanding of R3F itself.

My transition in writing vanilla Three.js to R3F for the first time was somewhat time-consuming — but not particularly challenging — I only had to be better at reading the documentation. Plus, I wrote it using a bit of TypeScript — so I had a classic “fixing type errors” moment (sigh).

I think the most noticeable change was the shift in mindset to think more component-ish — obviously — in which every object is treated as a component.

// vanilla Three.js
const DIRECTIONAL_LIGHT = new THREE.DirectionalLight(0xFFFFFF, 0.5)
DIRECTIONAL_LIGHT.position.set(-1, 1, 1)

// R3F
<directionalLight color={0xFFFFFF} intensity={0.5} position={[-1, 1, 1]} />

And the most notable thing for me is one of the R3F built-in hooks — useFrame. As stated in the R3F documentationuseFrame enables the execution of code on every rendered frame — like running effects, updating controls, and so on — which makes animating easy!

// vanilla Three.js
const animate = () => {
  requestAnimationFrame(animate)

  for (let i = 0; i < OBJ.LIMIT; i++) {
    OBJ.STORE[i].position.y -= OBJ.SPEED
  }
  RENDERER.render(SCENE, CAMERA)
}
animate()

// R3F
useFrame(() => {
  MESH_REF.current.position.y -= OBJ.SPEED
}

Not forgetting to mention that useThree is also rad!

And here is the result.

Colordrop — R3F

A colorful drop effect. This is my first attempt at rewriting the previous colorful drop effect using React Three Fiber.

  • Three.js
  • React Three Fiber
  • React