useLoader Hook
Import
import { useLoader } from '@react-three/fiber'
Video Lecture
Section | Video Links | |
---|---|---|
useLoader Hook |
Description
The useLoader hook is used in React Three Fiber to pre-cache any assets in memory, such as images or 3D models for later use in the scene.
The useLoader
hook, uses any Three.js loader module as its first argument. In this example, we will pass it the THREE.TextureLoader
module. This will be used to texture our icosahedrons rather than using a single color as we've seen so far.
const texture = useLoader(THREE.TextureLoader, './img/grid.png')
The second argument is the URL of the asset to use. The URL in the above example, points to a relative location from the perspective of our web server serving our application code.
We will need to add this image to our project.
Create a new folder named img
under the existing ./public/
folder.
Right-click the grid image below, and use the option Save image as
, to save it into the new folder ./public/img/
.
After the image is loaded, we can assign it to the materials map
property.
There are several ways to do this. For example, if using a meshBasicMaterial
.
<meshBasicMaterial map="{texture}"></meshBasicMaterial>
material={new THREE.MeshBasicMaterial({ map: texture })}
const material = new THREE.MeshBasicMaterial()
material.map = texture
Note that any assets loaded with useLoader
are cached by default. The URLs act as cache-keys. This allows you to re-use the same asset anywhere within the component tree.
./src/App.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
|
Working Example
Useful Links
useLoader (Working Example) | sbedit.net |
useLoader | docs.pmnd.rs |
GitHub Branch
git clone https://github.com/Sean-Bradley/React-Three-Fiber-Boilerplate.git
cd React-Three-Fiber-Boilerplate
git checkout useLoader
npm install
npm start