• Stars
    star
    25,320
  • Rank 767 (Top 0.02 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 5 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🇨🇭 A React renderer for Three.js

@react-three/fiber

Version Downloads Twitter Discord Open Collective ETH BTC

react-three-fiber is a React renderer for threejs.

Build your scene declaratively with re-usable, self-contained components that react to state, are readily interactive and can participate in React's ecosystem.

npm install three @types/three @react-three/fiber

Does it have limitations?

None. Everything that works in Threejs will work here without exception.

Is it slower than plain Threejs?

No. There is no overhead. Components render outside of React. It outperforms Threejs in scale due to Reacts scheduling abilities.

Can it keep up with frequent feature updates to Threejs?

Yes. It merely expresses Threejs in JSX, <mesh /> dynamically turns into new THREE.Mesh(). If a new Threejs version adds, removes or changes features, it will be available to you instantly without depending on updates to this library.

What does it look like?

Let's make a re-usable component that has its own state, reacts to user-input and participates in the render-loop. (live demo).
import { createRoot } from 'react-dom/client'
import React, { useRef, useState } from 'react'
import { Canvas, useFrame } from '@react-three/fiber'

function Box(props) {
  // This reference gives us direct access to the THREE.Mesh object
  const ref = useRef()
  // Hold state for hovered and clicked events
  const [hovered, hover] = useState(false)
  const [clicked, click] = useState(false)
  // Subscribe this component to the render-loop, rotate the mesh every frame
  useFrame((state, delta) => (ref.current.rotation.x += delta))
  // Return the view, these are regular Threejs elements expressed in JSX
  return (
    <mesh
      {...props}
      ref={ref}
      scale={clicked ? 1.5 : 1}
      onClick={(event) => click(!clicked)}
      onPointerOver={(event) => hover(true)}
      onPointerOut={(event) => hover(false)}>
      <boxGeometry args={[1, 1, 1]} />
      <meshStandardMaterial color={hovered ? 'hotpink' : 'orange'} />
    </mesh>
  )
}

createRoot(document.getElementById('root')).render(
  <Canvas>
    <ambientLight intensity={Math.PI / 2} />
    <spotLight position={[10, 10, 10]} angle={0.15} penumbra={1} decay={0} intensity={Math.PI} />
    <pointLight position={[-10, -10, -10]} decay={0} intensity={Math.PI} />
    <Box position={[-1.2, 0, 0]} />
    <Box position={[1.2, 0, 0]} />
  </Canvas>,
)
Show TypeScript example
npm install @types/three
import * as THREE from 'three'
import { createRoot } from 'react-dom/client'
import React, { useRef, useState } from 'react'
import { Canvas, useFrame, ThreeElements } from '@react-three/fiber'

function Box(props: ThreeElements['mesh']) {
  const ref = useRef<THREE.Mesh>(null!)
  const [hovered, hover] = useState(false)
  const [clicked, click] = useState(false)
  useFrame((state, delta) => (ref.current.rotation.x += delta))
  return (
    <mesh
      {...props}
      ref={ref}
      scale={clicked ? 1.5 : 1}
      onClick={(event) => click(!clicked)}
      onPointerOver={(event) => hover(true)}
      onPointerOut={(event) => hover(false)}>
      <boxGeometry args={[1, 1, 1]} />
      <meshStandardMaterial color={hovered ? 'hotpink' : 'orange'} />
    </mesh>
  )
}

createRoot(document.getElementById('root') as HTMLElement).render(
  <Canvas>
    <ambientLight intensity={Math.PI / 2} />
    <spotLight position={[10, 10, 10]} angle={0.15} penumbra={1} decay={0} intensity={Math.PI} />
    <pointLight position={[-10, -10, -10]} decay={0} intensity={Math.PI} />
    <Box position={[-1.2, 0, 0]} />
    <Box position={[1.2, 0, 0]} />
  </Canvas>,
)

Live demo: https://codesandbox.io/s/icy-tree-brnsm?file=/src/App.tsx

Show React Native example

This example relies on react 18 and uses expo-cli, but you can create a bare project with their template or with the react-native CLI.

# Install expo-cli, this will create our app
npm install expo-cli -g
# Create app and cd into it
expo init my-app
cd my-app
# Install dependencies
npm install three @react-three/fiber@beta react@rc
# Start
expo start

Some configuration may be required to tell the Metro bundler about your assets if you use useLoader or Drei abstractions like useGLTF and useTexture:

// metro.config.js
module.exports = {
  resolver: {
    sourceExts: ['js', 'jsx', 'json', 'ts', 'tsx', 'cjs'],
    assetExts: ['glb', 'png', 'jpg'],
  },
}
import React, { useRef, useState } from 'react'
import { Canvas, useFrame } from '@react-three/fiber/native'
function Box(props) {
  const mesh = useRef(null)
  const [hovered, setHover] = useState(false)
  const [active, setActive] = useState(false)
  useFrame((state, delta) => (mesh.current.rotation.x += delta))
  return (
    <mesh
      {...props}
      ref={mesh}
      scale={active ? 1.5 : 1}
      onClick={(event) => setActive(!active)}
      onPointerOver={(event) => setHover(true)}
      onPointerOut={(event) => setHover(false)}>
      <boxGeometry args={[1, 1, 1]} />
      <meshStandardMaterial color={hovered ? 'hotpink' : 'orange'} />
    </mesh>
  )
}
export default function App() {
  return (
    <Canvas>
      <ambientLight intensity={Math.PI / 2} />
      <spotLight position={[10, 10, 10]} angle={0.15} penumbra={1} decay={0} intensity={Math.PI} />
      <pointLight position={[-10, -10, -10]} decay={0} intensity={Math.PI} />
      <Box position={[-1.2, 0, 0]} />
      <Box position={[1.2, 0, 0]} />
    </Canvas>
  )
}

Documentation, tutorials, examples

Visit docs.pmnd.rs

First steps

You need to be versed in both React and Threejs before rushing into this. If you are unsure about React consult the official React docs, especially the section about hooks. As for Threejs, make sure you at least glance over the following links:

  1. Make sure you have a basic grasp of Threejs. Keep that site open.
  2. When you know what a scene is, a camera, mesh, geometry, material, fork the demo above.
  3. Look up the JSX elements that you see (mesh, ambientLight, etc), all threejs exports are native to three-fiber.
  4. Try changing some values, scroll through our API to see what the various settings and hooks do.

Some helpful material:

Ecosystem

There is a vibrant and extensive eco system around three-fiber, full of libraries, helpers and abstractions.

How to contribute

If you like this project, please consider helping out. All contributions are welcome as well as donations to Opencollective, or in crypto BTC: 36fuguTPxGCNnYZSRdgdh6Ea94brCAjMbH, ETH: 0x6E3f79Ea1d0dcedeb33D3fC6c34d2B1f156F2682.

Backers

Thank you to all our backers! 🙏

Contributors

This project exists thanks to all the people who contribute.

More Repositories

1

zustand

🐻 Bear necessities for state management in React
TypeScript
40,808
star
2

react-spring

✌️ A spring physics based React animation library
TypeScript
27,160
star
3

jotai

👻 Primitive and flexible state management for React
TypeScript
16,893
star
4

use-gesture

👇Bread n butter utility for component-tied mouse/touch gestures in React and Vanilla Javascript.
TypeScript
8,537
star
5

valtio

💊 Valtio makes proxy-state simple for React and Vanilla
TypeScript
8,257
star
6

drei

🥉 useful helpers for react-three-fiber
JavaScript
7,122
star
7

leva

🌋 React-first components GUI
TypeScript
4,528
star
8

gltfjsx

🎮 Turns GLTFs into JSX components
JavaScript
3,949
star
9

use-cannon

👋💣 physics based hooks for @react-three/fiber
TypeScript
2,654
star
10

react-three-next

React Three Fiber, Threejs, Nextjs starter
JavaScript
2,140
star
11

postprocessing

A post processing library for three.js.
JavaScript
2,100
star
12

racing-game

🏎 Open source racing game developed by everyone willing
TypeScript
2,094
star
13

react-xr

🤳 VR/AR with react-three-fiber
TypeScript
1,890
star
14

react-three-flex

💪📦 Flexbox for react-three-fiber
TypeScript
1,606
star
15

suspend-react

🚥 Async/await for React components
TypeScript
1,308
star
16

react-postprocessing

📬 postprocessing for react-three-fiber
JavaScript
1,009
star
17

detect-gpu

Classifies GPUs based on their 3D rendering benchmark score allowing the developer to provide sensible default settings for graphically intensive applications.
TypeScript
979
star
18

lamina

🍰 An extensible, layer based shader material for ThreeJS
TypeScript
976
star
19

its-fine

🐶🔥 A collection of escape hatches for React.
TypeScript
891
star
20

react-use-measure

🙌 Utility to measure view bounds
TypeScript
799
star
21

react-nil

⃝ A react null renderer
TypeScript
772
star
22

react-three-rapier

🤺 Rapier physics in React
TypeScript
765
star
23

maath

🪶 Math helpers for the rest of us
TypeScript
755
star
24

threejs-journey

⚛️ Bruno Simons journey demos in React
TypeScript
685
star
25

three-stdlib

📚 Stand-alone library of threejs examples designed to run without transpilation in node & browser
JavaScript
624
star
26

react-three-editor

🔌 A one of a kind scene editor that writes changes back into your code
TypeScript
602
star
27

react-three-a11y

♿️ Accessibility tools for React Three Fiber
TypeScript
507
star
28

react-zdog

⚡️🐶 React bindings for zdog
JavaScript
441
star
29

use-asset

📦 A promise caching strategy for React Suspense
TypeScript
414
star
30

react-three-offscreen

📺 Offscreen worker canvas for react-three-fiber
TypeScript
397
star
31

drei-vanilla

🍦 drei-inspired helpers for threejs
TypeScript
364
star
32

ecctrl

🕹️ A floating rigibody character controller
TypeScript
349
star
33

tunnel-rat

🐀 Non gratum anus rodentum
TypeScript
287
star
34

react-three-lgl

🔆 A React abstraction for the LGL Raycaster
TypeScript
260
star
35

market

📦 Download CC0 assets ready to use in your next 3D Project
JavaScript
249
star
36

react-three-csg

🚧 Constructive solid geometry for React
TypeScript
242
star
37

gltf-react-three

Convert GLTF files to React Three Fiber Components
JavaScript
230
star
38

component-material

🧩 Compose modular materials in React
TypeScript
161
star
39

env

💄 An app to create, edit, and preview HDR environment maps in the browser
TypeScript
143
star
40

use-p2

👋💣 2d physics hooks for @react-three/fiber
TypeScript
141
star
41

react-ogl

🦴 A barebones react renderer for ogl.
TypeScript
139
star
42

react-spring-examples

JavaScript
138
star
43

react-three-gpu-pathtracer

⚡️ A React abstraction for the popular three-gpu-pathtracer
TypeScript
125
star
44

react-three-lightmap

In-browser lightmap/AO baker for react-three-fiber and ThreeJS
TypeScript
123
star
45

cannon-es-debugger

Wireframe debugger for use with cannon-es https://github.com/react-spring/cannon-es
HTML
103
star
46

rafz

💍 One loop to frame them all.
TypeScript
96
star
47

website

Poimandres developer collective website
JavaScript
87
star
48

swc-jotai

Rust
85
star
49

assets

📦 Importable base64 encoded CC0 assets
Makefile
84
star
50

react-three-scissor

✂ Multiple scenes, one canvas! WebGL Scissoring implementation for React Three Fiber.
TypeScript
81
star
51

eslint-plugin-valtio

An eslint plugin for better valtio experience
JavaScript
69
star
52

react-spring.io

✌️ A spring physics based React animation library
TypeScript
56
star
53

react-three-babel

🛍 A Babel plugin that automatically builds the extend catalogue of known native Three.js elements
TypeScript
53
star
54

r3f-website

Website for React Three Fiber
JavaScript
26
star
55

market-assets

JavaScript
19
star
56

react-three-8thwall

JavaScript
17
star
57

drei-assets

JavaScript
16
star
58

discord

🤖 Poimandres Discord Bot
TypeScript
10
star
59

react-three-jolt

⚡ Jolt physics in React
CSS
10
star
60

branding

TypeScript
7
star
61

market-assets-do

JavaScript
5
star
62

envinfo

Easily collect useful information for bug reports
JavaScript
4
star
63

leva-wg

1
star