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




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>
  )
}
useState reactjs.org w3schools.com codesandbox.io

Working Example