Skip to content

useState

Import

import { useState } from 'react'

Video Lecture

Section Video Links
useState Hook useState Hook useState Hook

Description

The useState Hook is a React component that allows us to track state between function calls, and provide a way to modify it.

useState accepts an initial state and returns two values:

  1. The current state.
  2. A function that updates the state.

We should never directly update state in our components, but use the useState hook instead.

E.g.,

bad

let color = 'red'
// and then somewhere else in your component,
color = 'green' // bad

good

const [color, setColor] = useState('red')
// and then somewhere else in your component,
setColor('green')

Note

React re-renders components whenever its state or props change. Normally variables "disappear" when a function exits, but state variables are preserved by React.

In this example, we will use useState to modify our boxes depending on certain pointer events.

./src/Box.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
import { useRef, useState } from 'react'
import { useFrame } from '@react-three/fiber'

export default function Box(props) {
  const ref = useRef()
  const [hovered, setHover] = useState(false)
  const [rotate, setRotate] = useState(false)

  useFrame((_, delta) => {
    if (rotate) {
      ref.current.rotation.x += 1 * delta
      ref.current.rotation.y += 0.5 * delta
    }
  })

  return (
    <mesh
      {...props}
      ref={ref}
      scale={hovered ? [1.1, 1.1, 1.1] : [1, 1, 1]}
      onPointerDown={() => setRotate(!rotate)}
      onPointerOver={() => setHover(true)}
      onPointerOut={() => setHover(false)}
    >
      <boxGeometry />
      <meshBasicMaterial color={hovered ? 0xff0000 : 0x00ff00} wireframe />
    </mesh>
  )
}

Working Example

<>
useState reactjs.org w3schools.com sbedit.net

GitHub Branch

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

Comments