React - useState: Local State Management
This is what allows you to memorize and modify data in your components. Without it, your component is stateless (without state).
(the equivalent of our variable, kind of in the idea)
Why useState?
Before Hooks (Class Components)
// OLD - Class Component (verbose and complicated)
class CompteurOldSchool extends React.Component {
constructor(props) {
super(props)
this.state = { count: 0, name: '' }
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
this.setState({ count: this.state.count + 1 })
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<input
value={this.state.name}
onChange={e => this.setState({ name: e.target.value })}
/>
<button onClick={this.handleClick}>+1</button>
</div>
)
}
}
With useState (Functional Components)
// MODERN - Functional Component with useState
import { useState } from 'react'
function CompteurModerne() {
const [count, setCount] = useState(0)
const [name, setName] = useState('')
return (
<div>
<p>Count: {count}</p>
<input
value={name}
onChange={e => setName(e.target.value)}
/>
<button onClick={() => setCount(count + 1)}>+1</button>
</div>
)
}
Why is it better?
- Less code: 50% fewer lines
- More readable: no this.state everywhere
- 🚀 Simpler: no constructor or bind
- 💪 More powerful: custom hooks possible
useState - The Basics
Syntax and Usage
import { useState } from 'react'
function ExemplesUseState() {
// Basic syntax: [value, function_to_modify]
const [count, setCount] = useState(0) // Number
const [name, setName] = useState('') // String
const [isVisible, setIsVisible] = useState(true) // Boolean
const [items, setItems] = useState([]) // Array
const [user, setUser] = useState({}) // Object
return (
<div>
{/* Display the value */}
<p>Count: {count}</p>
{/* Modify the value */}
<button onClick={() => setCount(count + 1)}>+1</button>
<button onClick={() => setCount(0)}>Reset</button>
{/* Controlled input */}
<input
value={name}
onChange={e => setName(e.target.value)}
placeholder="Your name..."
/>
{/* Toggle boolean */}
<button onClick={() => setIsVisible(!isVisible)}>
{isVisible ? 'Hide' : 'Show'}
</button>
{isVisible && <p>I am visible!</p>}
</div>
)
}