useState
Import
import { useState } from 'react'
Video Lecture
| Section | Video Links |
|---|---|
| useState Hook | |
(Pay Per View)
You can use PayPal to purchase a one time viewing of this video for $1.49 USD.
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:
- The current state.
- 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 | |
Working Example
Useful Links
| 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































