Creating and Updating a State

Previously, when we want to use a React state, we mustcreate a class component:


RESETRUNFULL
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>);
   }}

With a React hook, we can rewrite the above example as a function component:

The setCount() function accepts a new state value and enqueues a re-render of the component.
RESETRUNFULL
function Example() {   // Declare a new state variable named "count", and an update function “setCount"
   const [count, setCount] = React.useState(0);    // initializes count to 0
   return (<div><p>You clicked {count} times</p>
                       <button onClick={() => setCount(count + 1)}>
                          Click me
                       </button> </div>);}

The class component is re-rendered when the state is set to the same value, while in the function component, setting the state to the same value doesn't cause a re-render.