DEV Community

kevin sims
kevin sims

Posted on

3

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) {
    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>)
  }
}

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 = () => {
   setCounter(counter++)
 }
 return (
  <div>
   <button onClick={onClick}>
    click me to change counter
   </button>
   <h1>{counter}</h1>
  </div>
 )
}

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.

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!

Top comments (0)

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay