React Three Fiber (R3F) is a React renderer for Three.js, allowing you to build 3D scenes using React components. It simplifies the process of working with Three.js by integrating it into the React ecosystem.
Regardless of the framework you choose, you'll need to install three (the core Three.js library) and @react-three/fiber. It's also highly recommended to install @react-three/drei, which provides useful helpers and abstractions.
npm install three @react-three/fiber @react-three/drei
# or
yarn add three @react-three/fiber @react-three/drei
Vite works well with React Three Fiber out of the box, offering a fast development experience.
npm create vite@latest my-r3f-app -- --template react
cd my-r3f-app
For TypeScript, select React as the framework and TypeScript or TypeScript + SWC when prompted.
npm install three @react-three/fiber @react-three/drei
# If using TypeScript, also install:
npm install @types/three --save-dev
npm run dev
You can then add a <Canvas> component from @react-three/fiber to your App.jsx (or App.tsx) to start building your 3D scene.
Create React App also works out of the box with React Three Fiber, requiring no special configuration.
npx create-react-app my-r3f-app --template typescript # Add --template typescript for TypeScript
cd my-r3f-app
npm install three @react-three/fiber @react-three/drei
npm start
You can then import Canvas from @react-three/fiber and start creating your 3D components within your React application.
Next.js requires a small additional configuration, especially for newer versions, to handle three.js modules correctly.
npx create-next-app@latest my-r3f-app
cd my-r3f-app
During the setup, you'll be asked if you want to use TypeScript; select yes.
npm install three @react-three/fiber @react-three/drei
next.config.js:
For Next.js 13.1 or later, you need to add three to the transpilePackages property in next.config.js to ensure proper transpilation of three.js modules.
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
transpilePackages: ['three'], // Add this line
};
module.exports = nextConfig;
For Next.js 13.0 or older, you might need to use next-transpile-modules.
npm run dev
When working with Next.js, especially with App Router, components that use React Hooks (like useFrame from R3F) need to be client-side components. You can achieve this by adding "use client"; at the top of your component file.