Skip to content

useState

Import

import { useState } from 'react'

Video Lecture

Section Video Links
useState Hook useState Hook useState Hook 

 (Pay Per View)

You can use PayPal to purchase a one time viewing of this video for $1.49 USD.

Pay Per View Terms

  • One viewing session of this video will cost the equivalent of $1.49 USD in your currency.
  • After successful purchase, the video will automatically start playing.
  • You can pause, replay and go fullscreen as many times as needed in one single session for up to an hour.
  • Do not refresh the browser since it will invalidate the session.
  • If you want longer-term access to all videos, consider purchasing full access through Udemy or YouTube Memberships instead.
  • This Pay Per View option does not permit downloading this video for later viewing or sharing.
  • All videos are Copyright © 2019-2025 Sean Bradley, all rights reserved.

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