Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Using Three.js with React

Introduction

Three.js is a popular JavaScript library for creating 3D graphics in the browser. When combined with React, it allows you to create rich, interactive 3D applications. This lesson will guide you through the process of integrating Three.js with React.

Setup

To get started, you will need to set up a React project with Three.js. Follow these steps:

  1. Install Node.js if you haven't already.
  2. Create a new React project using Create React App:
  3. npx create-react-app my-three-app
  4. Navigate to your project directory:
  5. cd my-three-app
  6. Install Three.js:
  7. npm install three

Basic Example

Here’s a simple example of how to create a spinning cube with Three.js in a React component:


import React, { useEffect, useRef } from 'react';
import * as THREE from 'three';

const SpinningCube = () => {
    const mountRef = useRef(null);

    useEffect(() => {
        const scene = new THREE.Scene();
        const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        const renderer = new THREE.WebGLRenderer();
        renderer.setSize(window.innerWidth, window.innerHeight);
        mountRef.current.appendChild(renderer.domElement);

        const geometry = new THREE.BoxGeometry();
        const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
        const cube = new THREE.Mesh(geometry, material);
        scene.add(cube);

        camera.position.z = 5;

        const animate = () => {
            requestAnimationFrame(animate);
            cube.rotation.x += 0.01;
            cube.rotation.y += 0.01;
            renderer.render(scene, camera);
        };

        animate();

        return () => {
            mountRef.current.removeChild(renderer.domElement);
        };
    }, []);

    return 
; }; export default SpinningCube;

Advanced Features

Once you're comfortable with the basics, consider exploring more advanced features:

  • Using shaders for advanced materials.
  • Loading 3D models using THREE.GLTFLoader.
  • Implementing physics using libraries like cannon-es or ammo.js.

Best Practices

Here are some best practices for using Three.js with React:

  1. Keep Three.js logic encapsulated within custom hooks or components.
  2. Optimize rendering with requestAnimationFrame.
  3. Use React.memo or PureComponent to prevent unnecessary re-renders.
  4. Handle window resizing to maintain aspect ratio.

FAQ

Can I use Three.js with other frameworks?

Yes, Three.js can be used with any JavaScript framework, including Vue and Angular.

Is Three.js suitable for production applications?

Absolutely! Many production applications use Three.js for 3D graphics.

Where can I find more resources to learn Three.js?

Check the official Three.js documentation for tutorials and examples.