Texture loading with useTexture

Back to Modules

Texture Loading with useTexture in React Three Fiber

useTexture is a convenient hook provided by @react-three/drei that simplifies the process of loading textures in React Three Fiber applications. It is the recommended approach for texture loading in modern R3F setups.

How to Use useTexture

1. Basic Usage (Single Texture):

To load a single texture and apply it to a material, you can pass the path to the texture file directly to useTexture.

import { useTexture } from '@react-three/drei';
import React from 'react';

function MyTexturedBox() {
  const texture = useTexture('/path/to/your/texture.jpg');

  return (
    <mesh>
      <boxGeometry args={[1, 1, 1]} />
      <meshStandardMaterial map={texture} />
    </mesh>
  );
}

export default MyTexturedBox;

2. Loading Multiple Textures:

When you need to load multiple textures (e.g., color map, normal map, roughness map for PBR materials), you can pass an array of texture paths to useTexture. The hook will return an array of loaded Texture objects in the same order as the input paths.

import { useTexture } from '@react-three/drei';
import React from 'react';

function PBRMaterialBox() {
  const [colorMap, normalMap, roughnessMap] = useTexture([
    '/path/to/color.jpg',
    '/path/to/normal.jpg',
    '/path/to/roughness.jpg',
  ]);

  return (
    <mesh>
      <sphereGeometry args={[1, 64, 64]} />
      <meshStandardMaterial
        map={colorMap}
        normalMap={normalMap}
        roughnessMap={roughnessMap}
      />
    </mesh>
  );
}

export default PBRMaterialBox;

3. Using an Object for Material Properties:

useTexture can also accept an object where keys correspond to material properties (like map, normalMap, aoMap) and values are the texture paths. This can make your code cleaner when dealing with multiple PBR textures.

import { useTexture } from '@react-three/drei';
import React from 'react';

function AdvancedTexturedObject() {
  const textures = useTexture({
    map: 'textures/PavingStones130_1K_Color.jpg',
    normalMap: 'textures/PavingStones130_1K_NormalGL.jpg',
    roughnessMap: 'textures/PavingStones130_1K_Roughness.jpg',
    aoMap: 'textures/PavingStones130_1K_AmbientOcclusion.jpg',
  });

  return (
    <mesh>
      <boxGeometry />
      <meshStandardMaterial {...textures} />
    </mesh>
  );
}

export default AdvancedTexturedObject;

Important Considerations: