### 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() // const group = new THREE.Group() // const mesh = new THREE.Mesh() // const material = new THREE.MeshNormalMaterial() // const geometry = new THREE.BoxGeometry(2, 2, 2) // mesh.material = material mesh.geometry = geometry group.add(mesh) scene.add(group) ``` -------------------------------- ### Declaring ShaderMaterial uniforms Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/objects.mdx Example of how to declare uniforms for a `shaderMaterial` component. ```jsx ``` -------------------------------- ### Metro bundler configuration Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/installation.mdx Configuration for Metro bundler to recognize assets like GLTF and image files when using `useLoader`, `useGLTF`, or `useTexture`. ```javascript // metro.config.js module.exports = { resolver: { sourceExts: ['js', 'jsx', 'json', 'ts', 'tsx', 'cjs', 'mjs'], assetExts: ['glb', 'gltf', 'png', 'jpg'] } } ``` -------------------------------- ### Loader extensions Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/hooks.mdx How to configure a loader by providing a callback as the third argument to `useLoader`, for example, to set up `DRACOLoader`. ```jsx import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader' useLoader(GLTFLoader, url, (loader) => { const dracoLoader = new DRACOLoader() dracoLoader.setDecoderPath('/draco-gltf/') loader.setDRACOLoader(dracoLoader) }) ``` -------------------------------- ### StrictMode Inheritance Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/tutorials/v9-migration-guide.mdx Demonstrates the updated usage of StrictMode, where it's inherited from the parent renderer. ```diff - - // ... - + // ... ``` -------------------------------- ### Extending JSX with ThreeElement Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/tutorials/v9-migration-guide.mdx Example of how to declare a custom element using `ThreeElement`. ```tsx import { type ThreeElement } from '@react-three/fiber' declare module '@react-three/fiber' { interface ThreeElements { customElement: ThreeElement } } extend({ CustomElement }) ``` -------------------------------- ### Using createRoot for Custom Canvas Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/canvas.mdx Example of creating and configuring a custom React root for rendering to an existing DOM canvas element, including event handling and resizing. ```jsx import * as THREE from 'three' import { extend, createRoot, events } from '@react-three/fiber' // Register the THREE namespace as native JSX elements. // See below for notes on tree-shaking extend(THREE) // Create a react root const root = createRoot(document.querySelector('canvas')) async function app() { // Configure the root, inject events optionally, set camera, etc // This *must* be called before render, and it must be awaited await root.configure({ events, camera: { position: [0, 0, 50] } }) // createRoot by design is not responsive, you have to take care of resize yourself window.addEventListener('resize', () => { root.configure({ size: { width: window.innerWidth, height: window.innerHeight } }) }) // Trigger resize window.dispatchEvent(new Event('resize')) // Render entry point root.render() // Unmount and dispose of memory // root.unmount() } app() ``` -------------------------------- ### Re-using geometries and materials globally Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/advanced/scaling-performance.mdx Example of defining and re-using `THREE.Geometry` and `THREE.Material` instances globally to reduce GPU overhead. ```jsx const red = new THREE.MeshLambertMaterial({ color: "red" }) const sphere = new THREE.SphereGeometry(1, 28, 28) function Scene() { return ( <> ``` -------------------------------- ### Basic Canvas Usage Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/canvas.mdx A simple example demonstrating how to use the Canvas component to render a basic scene with a point light and a sphere. ```jsx import React from 'react' import { Canvas } from '@react-three/fiber' const App = () => ( ) ``` -------------------------------- ### Attach - Explicit material and geometry Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/objects.mdx Example of explicitly attaching a material and geometry to a mesh using the `attach` prop. ```jsx ``` -------------------------------- ### Attach - Array elements Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/objects.mdx Examples of attaching objects to specific indices within an array property of its parent. ```jsx ``` -------------------------------- ### Declaring objects - Correct way Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/objects.mdx An example of how to declaratively define properties to avoid re-creation, using nested components for geometry and material. ```jsx ``` -------------------------------- ### Setting up the Canvas Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/your-first-scene.mdx Importing the Canvas component and rendering it in a React application. ```jsx import { createRoot } from 'react-dom/client' import { Canvas } from '@react-three/fiber' function App() { return (
) } createRoot(document.getElementById('root')).render() ``` -------------------------------- ### Migrating from global JSX to ThreeElements Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/tutorials/v9-migration-guide.mdx Shows the migration path from using global JSX namespace to `ThreeElements` for custom elements. ```diff -import { type Node } from '@react-three/fiber' - -declare global { - namespace JSX { - interface IntrinsicElements { - customElement: Node - } - } -} - -extend({ CustomElement }) +import { type ThreeElement } from '@react-three/fiber' + +declare module '@react-three/fiber' { + interface ThreeElements { + customElement: ThreeElement + } +} + +extend({ CustomElement }) ``` -------------------------------- ### Async GL prop - Promise Return Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/tutorials/v9-migration-guide.mdx Shows how the `gl` prop callback can now return a promise for async constructors like `WebGPURenderer`. ```tsx { // ... return renderer }} > ``` -------------------------------- ### Constructor arguments Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/objects.mdx Example of passing one-time constructor arguments to a three.js object via the `args` prop in React Three Fiber. ```jsx ``` -------------------------------- ### Shortcuts - SetScalar method Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/objects.mdx Example of using the `setScalar` method shortcut for properties that support it, like `scale` on a `Vector3`. ```jsx // Translates to ``` -------------------------------- ### Attach - Nested object properties Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/objects.mdx Examples of attaching an object to deeply nested properties of its parent using dash-case. ```jsx ``` -------------------------------- ### Attach - Custom add/remove functions (one-liner) Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/objects.mdx A more concise example of using a custom function for the `attach` prop to define add and remove logic. ```jsx (parent.add(self), () => parent.remove(self))} /> ``` -------------------------------- ### Attach - Custom add/remove functions Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/objects.mdx Example of using a custom function for the `attach` prop to define how an object is added and removed from its parent. ```jsx { parent.add(self) return () => parent.remove(self) }} /> ``` -------------------------------- ### Getting Mesh for Interaction Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/testing.mdx How to get the specific mesh instance from the scene to fire events on. ```js const mesh = renderer.scene.children[0] ``` -------------------------------- ### Creating a Mesh with Geometry and Material Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/your-first-scene.mdx Creating a mesh with BoxGeometry and MeshStandardMaterial, which automatically attach to their parent. ```jsx ``` -------------------------------- ### Reading state from outside of the component cycle Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/hooks.mdx Shows how to get the current state using `get()` from `useThree`. ```jsx function Foo() { const get = useThree((state) => state.get) ... get() // Get fresh state from anywhere you want ``` -------------------------------- ### Setting position and color with `.set()` in Three.js Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/your-first-scene.mdx Using the `.set()` method for position and color properties on a DirectionalLight in Three.js. ```jsx const light = new THREE.DirectionalLight() light.position.set(0, 0, 5) light.color.set('red') ``` -------------------------------- ### Correct Example (Shared Reference) Source: https://github.com/pmndrs/react-three-fiber/blob/master/packages/eslint-plugin/docs/rules/no-clone-in-loop.md This example shows a correct approach by creating a `THREE.Vector3` instance once outside the component, allowing it to be reused and mutated each frame within the `useFrame` loop, thus avoiding repeated memory allocation. ```js const tempVec = new THREE.Vector3() function Direction({ targetPosition }) { const ref = useRef() useFrame(() => { const direction = tempVec.copy(ref.current.position).sub(targetPosition).normalize() }) return } ``` -------------------------------- ### Run test suites Source: https://github.com/pmndrs/react-three-fiber/blob/master/CONTRIBUTING.md Run the project's test suites. Use the watch option to test live against changes. ```bash yarn ``` ```bash yarn test # or, to test live against changes yarn test:watch ``` -------------------------------- ### Incorrect Example Source: https://github.com/pmndrs/react-three-fiber/blob/master/packages/eslint-plugin/docs/rules/no-clone-in-loop.md This example demonstrates an incorrect pattern where a new vector is created using `clone()` inside the `useFrame` loop, leading to new object instantiation 60+ times a second and wasting large amounts of memory. ```js function Direction({ targetPosition }) { const ref = useRef() useFrame(() => { const direction = ref.current.position.clone().sub(targetPosition).normalize() }) return } ``` -------------------------------- ### Handling Pointer Down Event Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/tutorials/how-it-works.mdx Example of attaching an onPointerDown event handler to a mesh. ```jsx ... ``` -------------------------------- ### Asserting Children Count Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/testing.mdx Example of an assertion to check the number of children on a mesh. ```js expect(meshChildren.length).toBe(2) ``` -------------------------------- ### Manually build and link packages Source: https://github.com/pmndrs/react-three-fiber/blob/master/CONTRIBUTING.md Run this command if you need to manually build and link packages for local development via symlinks, typically handled by Preconstruct. ```bash yarn dev ``` -------------------------------- ### Loading status Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/hooks.mdx Get the loading status from a callback provided as the fourth argument to `useLoader`. ```jsx useLoader(loader, url, extensions, (xhr) => { console.log((xhr.loaded / xhr.total) * 100 + '% loaded') }) ``` -------------------------------- ### Enter prerelease mode Source: https://github.com/pmndrs/react-three-fiber/blob/master/CONTRIBUTING.md Specify a tag to enter prerelease mode for publishing. ```bash yarn changeset pre enter ``` -------------------------------- ### Accessing Scene Children Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/testing.mdx How to get the direct children of the scene from the test renderer instance. ```js const meshChildren = renderer.scene.children ``` -------------------------------- ### Mesh Event Handlers Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/events.mdx Example of various pointer and update event handlers on a mesh component. ```jsx console.log('click')} onContextMenu={(e) => console.log('context menu')} onDoubleClick={(e) => console.log('double click')} onWheel={(e) => console.log('wheel spins')} onPointerUp={(e) => console.log('up')} onPointerDown={(e) => console.log('down')} onPointerOver={(e) => console.log('over')} onPointerOut={(e) => console.log('out')} onPointerEnter={(e) => console.log('enter')} // see note 1 onPointerLeave={(e) => console.log('leave')} // see note 1 onPointerMove={(e) => console.log('move')} onPointerMissed={() => console.log('missed')} onUpdate={(self) => console.log('props have been updated')} /> ``` -------------------------------- ### BoxGeometry constructor arguments in Three.js Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/your-first-scene.mdx How to pass width, length, and depth arguments to BoxGeometry in plain Three.js. ```js new THREE.BoxGeometry(2, 2, 2) ``` -------------------------------- ### Custom Raycasting with useCamera Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/tutorials/how-it-works.mdx Demonstrates how to use the `raycast` prop with a custom ray provided by `useCamera` from `@react-three/drei`. ```jsx import { useCamera } from '@react-three/drei' return ``` -------------------------------- ### Loading multiple textures with useLoader Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/tutorials/loading-textures.mdx Demonstrates how to load multiple textures (color, displacement, normal, roughness, ambient occlusion) by passing an array of paths to `useLoader`. ```js const [colorMap, displacementMap, normalMap, roughnessMap, aoMap] = useLoader(TextureLoader, [ 'PavingStones092_1K_Color.jpg', 'PavingStones092_1K_Displacement.jpg', 'PavingStones092_1K_Normal.jpg', 'PavingStones092_1K_Roughness.jpg', 'PavingStones092_1K_AmbientOcclusion.jpg', ]) ``` -------------------------------- ### Attach - Object property Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/objects.mdx Example of attaching an object to a specific property of its parent. ```jsx ``` -------------------------------- ### Three.js equivalent of a React Three Fiber scene Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/your-first-scene.mdx The equivalent three.js code for setting up a scene with a camera, renderer, and a mesh with geometry and material. ```jsx const scene = new THREE.Scene() const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000) const renderer = new THREE.WebGLRenderer() renderer.setSize(width, height) document.querySelector('#canvas-container').appendChild(renderer.domElement) const mesh = new THREE.Mesh() mesh.geometry = new THREE.BoxGeometry() mesh.material = new THREE.MeshStandardMaterial() scene.add(mesh) function animate() { requestAnimationFrame(animate) renderer.render(scene, camera) } animate() ``` -------------------------------- ### Good: Animations with `react-spring` Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/advanced/pitfalls.mdx Example of using `react-spring` for declarative animations, which handles its own frame loop. ```jsx import { a, useSpring } from '@react-spring/three' function Signal({ active }) { const { x } = useSpring({ x: active ? 100 : 0 }) return ``` -------------------------------- ### Asserting Scale Update Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/testing.mdx Example of an assertion to check if the mesh's scale property has updated after an interaction. ```js expect(mesh.props.scale).toBe(1.5) ``` -------------------------------- ### Basic CSS Styles Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/your-first-scene.mdx CSS to ensure the root element takes full height for the 3D scene. ```css html,body,#root {height:100%;margin:unset;} ``` -------------------------------- ### Good: Using visibility instead of conditional mounting Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/advanced/pitfalls.mdx Correct way to switch between stages by controlling component visibility instead of mounting/unmounting them. ```jsx function Stage1(props) { return ( ... ``` -------------------------------- ### Accessing All Mesh Children Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/testing.mdx How to get all children of the first mesh, including geometry and materials, using `allChildren`. ```js const meshChildren = renderer.scene.children[0].allChildren ``` -------------------------------- ### Canvas Props Renamed Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/tutorials/v9-migration-guide.mdx Shows the change from `Props` to `CanvasProps` in the Canvas component signature. ```diff -function Canvas(props: Props) +function Canvas(props: CanvasProps) ``` -------------------------------- ### Stopping Event Propagation Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/events.mdx Example of how to stop event propagation and block events from objects behind the current one. ```jsx onPointerOver={e => { e.stopPropagation() // ... }} ``` -------------------------------- ### Dynamic JSX Types Usage Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/tutorials/v9-migration-guide.mdx Illustrates the change from importing `MeshProps` to using `ThreeElements['mesh']`. ```diff -import { MeshProps } from '@react-three/fiber' -type Props = MeshProps +import { ThreeElements } from '@react-three/fiber' +type Props = ThreeElements['mesh'] ``` -------------------------------- ### Adding lights to the scene Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/your-first-scene.mdx Adding ambient and directional lights to the Canvas component. ```jsx ``` -------------------------------- ### Using the 'attach' prop Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/tutorials/how-it-works.mdx Explicitly attaching material and geometry components to a mesh using the 'attach' prop. ```jsx ``` -------------------------------- ### Declaring objects - Incorrect way Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/objects.mdx An example of how NOT to declare objects, as properties will be re-created on every render. ```jsx ``` -------------------------------- ### Setting `intensity` on `AmbientLight` in Three.js Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/getting-started/your-first-scene.mdx The equivalent Three.js code for setting the intensity property of an AmbientLight. ```jsx const light = new THREE.AmbientLight() light.intensity = 0.1 ``` -------------------------------- ### Bad: `setState` in fast events Source: https://github.com/pmndrs/react-three-fiber/blob/master/docs/advanced/pitfalls.mdx An example of incorrectly using `setState` in a fast event handler like `onPointerMove`. ```jsx setX((x) => e.point.x)} /> ```