A Quick Look At Reacts useState
kevin sims
Posted on October 11, 2020
What's useState?
useState is a react hook. React Hooks are a new feature to React 16.8. Hooks allow us to use things like state, inside of functional components.
So when you usually make some state for a class component it'll look something like this
class FakeDate extends React.Component {
constructor(props) {
super(props);
this.state = {counter: 0};
this.handleClick = this.handleClick.bind(this);
}
handleClick = () => {
this.setState({counter: counter++})
}
render() {
return (
<div>
<button onClick={this.onClick}>click to change counter</button>
</div>
<h2>It is {this.state.date}.</h2>)
}
}
Now with hooks, we can utilize useState and write something like this
const Counter = () => {
const [counter, setCounter] = useState(0)
const onClick = () => {
setCounter(counter++)
}
return (
<div>
<button onClick={onClick}>
click me to change counter
</button>
<h1>{counter}</h1>
</div>
)
}
Pretty cool right?
A Deeper Look
When we useState, we no longer require a constructor or state object. Instead, we declare our state variable along with its setVariable partner. Now anytime you want to update that specific state variable you just call setVariable and pass it a value.
Is useState Better State?
Should you use the useState hook or the traditional state lifecycle?
Well, it depends if you want to use a functional or class component.
useState is simply a tool of convenience.
There will still be times where a class component is more useful than a functional component. Assess your needs and the answer will be obvious.
Conclusion
We have gone over the useState hook. I hope you've gained some knowledge from this. If you have any questions feel free to reach out to my twitter.
Thank you for reading and keep coding!
Posted on October 11, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 17, 2020