### Basic Setup Without Build Tools
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/installation.mdx
Minimal example demonstrating how to use React Three Fiber with ES Modules and `htm` without a build tool.
```jsx
import ReactDOM from 'https://esm.sh/react-dom'
import React, { useRef, useState } from 'https://esm.sh/react'
import { Canvas, useFrame } from 'https://esm.sh/@react-three/fiber'
import htm from 'https://esm.sh/htm'
const html = htm.bind(React.createElement)
ReactDOM.render(html`<${Canvas}>.../>`, document.getElementById('root'))
```
--------------------------------
### Full Example Without Build Tools
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/installation.mdx
A complete example showing a rotating box in React Three Fiber using ES Modules and `htm` without a build tool.
```jsx
import ReactDOM from 'https://esm.sh/react-dom'
import React, { useRef, useState } from 'https://esm.sh/react'
import { Canvas, useFrame } from 'https://esm.sh/@react-three/fiber'
import htm from 'https://esm.sh/htm'
const html = htm.bind(React.createElement)
function Box(props) {
const meshRef = useRef()
const [hovered, setHover] = useState(false)
const [active, setActive] = useState(false)
useFrame(() => (meshRef.current.rotation.x = meshRef.current.rotation.y += 0.01))
return html` setActive(!active)}
onPointerOver=${() => setHover(true)}
onPointerOut=${() => setHover(false)}
>
`
}
ReactDOM.render(
html` <${Canvas}>
<${Box} position=${[-1.2, 0, 0]} />
<${Box} position=${[1.2, 0, 0]} />
/>`,
document.getElementById('root'),
)
```
--------------------------------
### Vite.js Installation Steps
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/installation.mdx
Steps to create a new Vite.js application, install react-three-fiber, and start the development server.
```bash
# Create app
npm create vite my-app
# Select react as framework
# Install dependencies
cd my-app
npm install three @react-three/fiber
# Start development server
npm run dev
```
--------------------------------
### Basic 3D Scene Setup
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/your-first-scene.mdx
An example of setting up a basic 3D scene with a box mesh, Phong material, ambient light, and directional light using react-three-fiber.
```jsx
import { Canvas } from "@react-three/fiber";
export default function App() {
return (
);
}
```
--------------------------------
### Installation
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/introduction.mdx
Command to install react-three-fiber and its dependencies.
```bash
npm install three @types/three @react-three/fiber
```
--------------------------------
### Initial Installation
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/installation.mdx
Install core dependencies for react-three-fiber.
```bash
npm install three @react-three/fiber
```
--------------------------------
### Run examples locally
Source: https://github.com/pmndrs/react-three-fiber/blob/master/CONTRIBUTING.md
Execute project examples against the local library build.
```bash
yarn examples
```
--------------------------------
### Install `next-transpile-modules`
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/installation.mdx
Install `next-transpile-modules` for older Next.js versions to handle `three.js` transpilation.
```bash
npm install next-transpile-modules --save-dev
```
--------------------------------
### TypeScript Type Installation
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/introduction.mdx
Command to install TypeScript types for Three.js.
```bash
npm install @types/three
```
--------------------------------
### Installation
Source: https://github.com/pmndrs/react-three-fiber/blob/master/packages/eslint-plugin/README.md
Command to install the ESLint plugin.
```bash
npm install @react-three/eslint-plugin --save-dev
```
--------------------------------
### React Native Project Setup
Source: https://github.com/pmndrs/react-three-fiber/blob/master/packages/fiber/readme.md
Commands to initialize an Expo React Native project and install necessary dependencies for React Three Fiber.
```bash
# 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 react
# Start
expo start
```
--------------------------------
### React Three Fiber example
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/tutorials/how-it-works.mdx
A small React example demonstrating basic scene composition with Fiber components.
```jsx
import { Canvas } from '@react-three/fiber'
function MyApp() {
return (
)
}
```
--------------------------------
### Install Expo GL
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/installation.mdx
Command to automatically install `expo-gl` for React Native projects.
```bash
# Automatically install
expo install expo-gl
```
--------------------------------
### Installation
Source: https://github.com/pmndrs/react-three-fiber/blob/master/packages/test-renderer/README.md
Commands to install @react-three/fiber, three, and @react-three/test-renderer.
```bash
yarn add @react-three/fiber three
yarn add -D @react-three/test-renderer
```
--------------------------------
### TypeScript Basic Example
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/introduction.mdx
A basic react-three-fiber scene demonstrating a re-usable, interactive Box component with TypeScript.
```typescript
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'
import './styles.css'
function Box(props: ThreeElements['mesh']) {
const meshRef = useRef(null!)
const [hovered, setHover] = useState(false)
const [active, setActive] = useState(false)
useFrame((state, delta) => (meshRef.current.rotation.x += delta))
return (
setActive(!active)}
onPointerOver={(event) => setHover(true)}
onPointerOut={(event) => setHover(false)}>
)
}
createRoot(document.getElementById('root')).render(
,
)
```
--------------------------------
### Using React's `act` for Testing
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/tutorials/v9-migration-guide.mdx
Example of using `act` from `react` to test `react-three-fiber` components.
```tsx
import { act } from 'react'
import { createRoot } from '@react-three/fiber'
const store = await act(async () => createRoot(canvas).render())
console.log(store.getState())
```
--------------------------------
### Basic React Native component with GLTF model
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/installation.mdx
Example of a React Native component using `@react-three/fiber/native` and `@react-three/drei/native` to load and display a GLTF model within a Canvas.
```jsx
import { Suspense } from 'react'
import { Canvas } from '@react-three/fiber/native'
import { useGLTF } from '@react-three/drei/native'
import modelPath from './path/to/model.glb'
function Model(props) {
const gltf = useGLTF(modelPath)
return
}
export default function App() {
return (
)
}
```
--------------------------------
### Shareable configs - All
Source: https://github.com/pmndrs/react-three-fiber/blob/master/packages/eslint-plugin/README.md
Example of extending the 'all' configuration.
```json
"extends": [
"plugin:@react-three/all"
]
```
--------------------------------
### Install dependencies
Source: https://github.com/pmndrs/react-three-fiber/blob/master/CONTRIBUTING.md
Install project dependencies using Yarn 1.
```bash
yarn
```
--------------------------------
### React Native Project Setup with Expo
Source: https://github.com/pmndrs/react-three-fiber/blob/master/readme.md
Commands to initialize a React Native project using Expo CLI and install necessary dependencies for React Three Fiber.
```bash
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
```
--------------------------------
### Install React Three Test Renderer
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/testing.mdx
Command to install the testing library as a development dependency.
```bash
npm install @react-three/test-renderer --save-dev
```
--------------------------------
### Configuration - Recommended
Source: https://github.com/pmndrs/react-three-fiber/blob/master/packages/eslint-plugin/README.md
Example of extending the recommended configuration in .eslintrc.json.
```json
"extends": [
"plugin:@react-three/recommended"
]
```
--------------------------------
### useLoader Accepts Loader Instance
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/tutorials/v9-migration-guide.mdx
Demonstrates how `useLoader` can accept a `GLTFLoader` instance directly, allowing for controlled pooling and setup.
```jsx
import { GLTFLoader } from 'three/addons'
import { useLoader } from '@react-three/fiber'
function Model() {
const gltf = useLoader(GLTFLoader, '/path/to/model.glb')
// ...
}
// or,
const loader = new GLTFLoader()
function Model() {
const gltf = useLoader(loader, '/path/to/model.glb')
// ...
}
```
--------------------------------
### Create React Native App
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/installation.mdx
Commands to create a new Expo or bare React Native application.
```bash
# Create a managed/bare app
npx create-expo-app
cd my-app
# or
# Create and link bare app
npx react-native init my-app
npx install-expo-modules@latest
cd my-app
```
--------------------------------
### React Native Basic Example
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/introduction.mdx
A basic react-three-fiber scene for React Native demonstrating a re-usable, interactive Box component.
```jsx
import React, { useRef, useState } from 'react'
import { Canvas, useFrame } from '@react-three/fiber/native'
function Box(props) {
const meshRef = useRef(null)
const [hovered, setHover] = useState(false)
const [active, setActive] = useState(false)
useFrame((state, delta) => (meshRef.current.rotation.x += delta))
return (
setActive(!active)}
onPointerOver={(event) => setHover(true)}
onPointerOut={(event) => setHover(false)}>
)
}
export default function App() {
return (
)
}
```
--------------------------------
### Initial Test File Setup
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/testing.mdx
Basic structure for an `App.test.js` file with two initial test cases using `ReactThreeTestRenderer`.
```jsx
import ReactThreeTestRenderer from '@react-three/test-renderer'
import { MyRotatingBox } from './App'
test('mesh to have two children', async () => {
const renderer = await ReactThreeTestRenderer.create()
})
test('click event makes box bigger', async () => {
const renderer = await ReactThreeTestRenderer.create()
})
```
--------------------------------
### Pointer Capture Example
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/events.mdx
Demonstrates how to use `stopPropagation`, `setPointerCapture`, and `releasePointerCapture` on pointer down and up events.
```jsx
onPointerDown={e => {
// Only the mesh closest to the camera will be processed
e.stopPropagation()
// You may optionally capture the target
e.target.setPointerCapture(e.pointerId)
}}
onPointerUp={e => {
e.stopPropagation()
// Optionally release capture
e.target.releasePointerCapture(e.pointerId)
}}
```
--------------------------------
### Multi-materials with explicit order
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/objects.mdx
Example demonstrating how to attach multiple materials to a mesh using an array and explicit indexing.
```jsx
{colors.map((color, index) => )}
```
--------------------------------
### `useGraph`
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/hooks.mdx
Example demonstrating how to use `useGraph` to create a memoized, named object/material collection from an `Object3D`.
```jsx
import { useLoader, useGraph } from '@react-three/fiber'
function Model(url) {
const scene = useLoader(OBJLoader, url)
const { nodes, materials } = useGraph(scene)
return
}
```
--------------------------------
### Next.js 13.1+ `next.config.js` Configuration
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/installation.mdx
Configuration for `next.config.js` to transpile `three.js` packages in Next.js 13.1 or later.
```js
transpilePackages: ['three'],
```
--------------------------------
### Act example (using jest)
Source: https://github.com/pmndrs/react-three-fiber/blob/master/packages/test-renderer/markdown/rttr.md
An example demonstrating the use of `act()` with Jest to test component updates over frames.
```tsx
import ReactThreeTestRenderer from '@react-three/test-renderer'
const Mesh = () => {
const meshRef = React.useRef()
useFrame((_, delta) => {
meshRef.current.rotation.x += delta
})
return (
)
}
const renderer = await ReactThreeTestRenderer.create()
expect(renderer.scene.children[0].instance.rotation.x).toEqual(0)
await ReactThreeTestRenderer.act(async () => {
await renderer.advanceFrames(2, 1)
})
expect(renderer.scene.children[0].instance.rotation.x).toEqual(2)
```
--------------------------------
### Basic Instancing Example
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/advanced/scaling-performance.mdx
Demonstrates how to use InstancedMesh to render many objects with a single draw call, setting their positions in a useEffect hook.
```jsx
function Instances({ count = 100000, temp = new THREE.Object3D() }) {
const instancedMeshRef = useRef()
useEffect(() => {
// Set positions
for (let i = 0; i < count; i++) {
temp.position.set(Math.random(), Math.random(), Math.random())
temp.updateMatrix()
instancedMeshRef.current.setMatrixAt(i, temp.matrix)
}
// Update the instance
instancedMeshRef.current.instanceMatrix.needsUpdate = true
}, [])
return (
)
}
```
--------------------------------
### Basic useFrame example
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/tutorials/basic-animations.mdx
Demonstrates how to use the `useFrame` hook to execute code on every render frame within a Fiber component.
```jsx
import { useFrame } from '@react-three/fiber'
function MyAnimatedBox() {
useFrame(() => {
console.log("Hey, I'm executing every frame!")
})
return (
)
}
```
--------------------------------
### Share materials and geometries
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/advanced/pitfalls.mdx
Example of sharing geometries and materials using `useMemo` to avoid re-creation costs.
```jsx
const geom = useMemo(() => new BoxGeometry(), [])
const mat = useMemo(() => new MeshBasicMaterial(), [])
return items.map(i =>
+
+
+
```
--------------------------------
### Basic Usage Example
Source: https://github.com/pmndrs/react-three-fiber/blob/master/packages/test-renderer/README.md
Demonstrates how to create a test renderer instance and assert against the scene graph.
```tsx
import ReactThreeTestRenderer from '@react-three/test-renderer'
const renderer = await ReactThreeTestRenderer.create(
,
)
// assertions using the TestInstance & Scene Graph
console.log(renderer.toGraph())
```
--------------------------------
### Correct Example (useMemo)
Source: https://github.com/pmndrs/react-three-fiber/blob/master/packages/eslint-plugin/docs/rules/no-clone-in-loop.md
This example illustrates another correct method using `useMemo` to create a `THREE.Vector3` instance once within the component's lifecycle. This vector is then reused and modified each frame, preventing unnecessary object creation in the `useFrame` loop.
```js
function Direction({ targetPosition }) {
const ref = useRef()
const tempVec = useMemo(() => new THREE.Vector3())
useFrame(() => {
const direction = tempVec.copy(ref.current.position).sub(targetPosition).normalize()
})
return
}
```
--------------------------------
### Good: `lerp` with `useFrame` for animations
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/advanced/pitfalls.mdx
Example of using `THREE.MathUtils.lerp` within `useFrame` for smooth animations.
```jsx
function Signal({ active }) {
const meshRef = useRef()
useFrame((state, delta) => {
meshRef.current.position.x = THREE.MathUtils.lerp(meshRef.current.position.x, active ? 100 : 0, 0.1)
})
return
```
--------------------------------
### Manual Tree-shaking with extend
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/canvas.mdx
Example showing how to manually enable tree-shaking by extending react-three-fiber with specific Three.js components.
```jsx
import { extend, createRoot } from '@react-three/fiber'
import { Mesh, BoxGeometry, MeshStandardMaterial } from 'three'
extend({ Mesh, BoxGeometry, MeshStandardMaterial })
createRoot(canvas).render(
<>
>,
)
```
--------------------------------
### Shortcuts - Set method
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/objects.mdx
Example of using the `.set()` method shortcut for properties like `position` (array) and `color` (string).
```jsx
```
--------------------------------
### Bad: Conditional mounting of components
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/advanced/pitfalls.mdx
An example of conditionally mounting components based on state, which can be expensive due to re-initialization.
```jsx
{
stage === 1 &&
}
{
stage === 2 &&
}
{
stage === 3 &&
}
```
--------------------------------
### Equivalent three.js code
Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/tutorials/how-it-works.mdx
The three.js equivalent of the React Three Fiber example, showing how objects are instantiated and composed.
```js
import * as THREE from 'three'
const scene = new THREE.Scene() //