useTexture in React Three FiberuseTexture 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.
useTextureTo 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;
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;
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;
useTexture is wrapped in a <Suspense> boundary to handle the loading state.useTexture can cause a runtime error. Consider using an ErrorBoundary to gracefully handle such issues.Texture object's properties, such as repeat, wrapS, and wrapT, to control how the texture is applied and tiled on your mesh.