Skip to content

useRef Hook

Import

import { useRef } from 'react'

Video Lecture

Section Video Links
useRef Hook useRef Hook useRef Hook

Description

If you want to read or modify the properties of a component instance at run time, then it is beneficial to have some kind of reference to that instance.

In this example, I get a reference to each of the Box component instances, which are actually each a THREE.Mesh under the hood, and log them to the console.

I will use the React useRef hook.

const instanceRef = useRef(initialValue)

The initial value, if not set, will be undefined until it is initialized when the JSX is rendered.

You have the option to set an initialValue. E.g., {}, [], or 1, or any value or object you need it to be, to act as a default until the reference is finally initialized.

./src/Box.jsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import { useRef } from 'react'

export default function Box(props) {
  const ref = useRef()
  console.log(ref)

  return (
    <mesh {...props} ref={ref}>
      <boxGeometry />
      <meshBasicMaterial color={0x00ff00} wireframe />
    </mesh>
  )
}

Note

Accessing a ref outside a hook, as I do in line 5, is not recommended. We will discuss this further in the next lesson. In this lesson it is important just to know that ref exists and that it can be used to imperatively interact with the inner properties and methods of a component instance.

If you look at the console, you will see the object properties written twice. This is because we added two Boxes to the scene. You can navigate the object trees and see that they have different positions and name in the scene.

Another important thing to note about useRef, is that it is mutable. Also, modifying it, or any property of it, won't cause a re-render of the component instance to happen, unlike changing props or state.

useRef reactjs.org w3schools.com

GitHub Branch

git clone https://github.com/Sean-Bradley/React-Three-Fiber-Boilerplate.git
cd React-Three-Fiber-Boilerplate
git checkout useRef
npm install
npm start

Comments