Introduction to React
The useState Hook
Before the 16.8 addition, you had to write class components to use state. The useState Hook lets you access state from functional components, without having to write class components.
Code example: Counter
The following example shows a counter where the user can increment the value by clicking the button.
import React, { useState } from 'react';function Example() {// Declare a new state variable, which we'll call "count"const [count, setCount] = useState(0);return (<div><p>You clicked {count} times</p><button onClick={() => setCount(count + 1)}>Click me</button></div>);}
Code example: Equivalent class component
class Example extends React.Component {constructor(props) {super(props);this.state = {count: 0};}render() {return (<div><p>You clicked {this.state.count} times</p><button onClick={() => this.setState({ count: this.state.count + 1 })}>Click me</button></div>);}}
As you can see we can drop the constructor when working with functional components. We also don’t have to deal with this. Instead we can call useState directly inside of the component. Finally, we don’t need to call the render() method.