Skip to content


 Zabbix
 Grafana
 Prometheus
 React Three Fiber
 Threejs and TypeScript
 SocketIO and TypeScript
 Blender Topological Earth
 Sweet Home 3D
 Design Patterns Python
 Design Patterns TypeScript
   
 Course Coupon Codes
Three.js and TypeScript
Kindle Edition
$6.99 $9.99 Paperback 
$22.99 $29.99




Design Patterns in TypeScript
Kindle Edition
$6.99 $9.99 Paperback
$11.99 $19.99




Design Patterns in Python
Kindle Edition
$6.99 $9.99 Paperback
$11.99 $19.99




useEffect Hook

Import

import { useEffect } from 'react'

Video Lecture

Section Video Links
useEffect Hook useEffect Hook useEffect Hook

Description

In the last example, there was a very subtle error which you might not have picked up if I didn't bring it to your attention.

When I used console.log(ref) in the last example, the Mesh hadn't actually finished being created in Three.js scene yet. So, if we needed to do any logic on that data within our script, then we would have needed to make sure that it actually existed first, otherwise ref.current would have been still undefined. This is because we tried to access ref and more specifically, it's current property, before it had been set when the JSX was converted into a Three.js object.

A way to improve on my last example would be to use the React useEffect hook.

./src/Box.jsx

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

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

  useEffect(() => {
    console.log(ref.current)
  })

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

The useEffect hook executes after the function returns the generated component instance within in it, which means the any ref will be assigned before the useEffect hook gets called.

useEffect reactjs.org w3schools.com codesandbox.io
useLayoutEffect reactjs.org

Working Example

GitHub Branch

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