DEV Community

kevin sims
kevin sims

Posted on

A Quick Look At Reacts useState

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) {
    this.state = {counter: 0};
    this.handleClick = this.handleClick.bind(this);

  handleClick = () => {
    this.setState({counter: counter++})

  render() {
    return (
      <button onClick={this.onClick}>click to change counter</button>
<h2>It is {}.</h2>)

Enter fullscreen mode Exit fullscreen mode

Now with hooks, we can utilize useState and write something like this

const Counter = () => {
 const [counter, setCounter] = useState(0)
 const onClick = () => {
 return (
   <button onClick={onClick}>
    click me to change counter

Enter fullscreen mode Exit fullscreen mode

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.


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!

Top comments (0)