Creating and Updating a State

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


RESETRUNFULL
<!DOCTYPE html><html>
  <head>
    <meta charset="UTF-8" />
    <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
  </head>
  <body>
    <div></div>
    <script type="text/babel">
      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>);
        }
      }
      const root = ReactDOM.createRoot(document.querySelector("div"));
      root.render(<Example/>);
    </script>
  </body></html>

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
<!DOCTYPE html><html>
  <head>
    <meta charset="UTF-8" />
    <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
  </head>
  <body>
    <div></div>
    <script type="text/babel">
      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>);
      }
      const root = ReactDOM.createRoot(document.querySelector("div"));
      root.render(<Example/>);
    </script>
  </body></html>

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.