24
loading...
This website collects cookies to deliver better user experience
useState
in particular from a beginner's point of view.initial state
and returns a state value and a function to update it.import { useState } from 'react'
React.useState
useState
hook at top of the file, and a handful of CSS styles to keep things centered and clean enough.App
, which is rendering increment and decrement buttons and a count
text in between. This count will render every time the state gets updated by the button clicks.count
in this case, and returns a pair of variables, count
and setCount
, where count
is the current state (currently set to 0) whereas setCount
is a function which updates it asynchronously.6
, we are using array destructuring to return the pair of variables at array index of 0 & 1.onClick
event, which triggers an anonymous function, which increments or decrements the count variable using the setCount
function. This click even results in the re-rendering of the count
state.count
state variable, we are allowed to use different data types such as objects, arrays, strings, boolean, etc.const [firstname, setFirstname] = useState("")
const [age, setAge] = useState(0)
const [isLoggedin, setIsLoggedin] = useState(false)
const [form, setForm] = useState({
username : "",
password : ""
})
useState
hook is a new addition to the React library, it somewhat does the same thing as this.state
used with class-based components. class
based component.class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
// change code below this line
increment() {
this.setState({
count: this.state.count + 1
});
};
decrement() {
this.setState({
count: this.state.count - 1
});
};
render() {
return (
<div>
<button className='inc' onClick={(e) => this.increment(e)}>Increment!</button>
<button className='dec' onClick={(e) => this.decrement(e)}>Decrement!</button>
<h1>Current Count: {this.state.count}</h1>
</div>
);
}
};
this.state
?this.state
const [lastname, setLastname] = useState(null)
const [firstname, setFirstname] = useState(null)
const [age, setAge] = useState(0)
const [islogin, setIslogin] = useState({
username : "",
password : ""
})
useState
(or any other hook) inside a function component.function App(){
if(true){
const [count, setCount] = useState(0)
}
}
function incrementCount(){
count = count + 1
}
function incrementCount(){
setCount(count + 1)
}
anonymous function
like how we used it in the first counter application.initial state
, and don't want unexpected rendering.setCount(count + 1)
setCount(prevState => prevState + 1)
prevState
ensures us to give us current value of count
no matter what, and in fact a better and recommended way to write hooks!