2

What's the difference between

function Example() {
  const [count, setCount] = useState(0);

and

function Example() {
  const count = 0;

with respect to the semantics of the count variable?

In addition to the existence of the setCount method, what are the advantages of using the useState hook?

ewerton
  • 427
  • 1
  • 6
  • 13

1 Answers1

4

The main reason is that if you use setCount without the count from useState, the view wont know it must re-render, they both go together so it knows how to be in sync.

Every time you use setCount, it does a full render again.

import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const [count, setCount] = useState(0);

  function onClick() {
    setCount(count+1);
  }

  return (
    <div className="App">
      <h1 onClick={onClick}>{count}</h1>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const count = 0;
  const [, setCount] = useState(count);

  function onClick() {
    setCount(count+1);
  }

  return (
    <div className="App">
      <h1 onClick={onClick}>{count}</h1>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Ion
  • 1,262
  • 12
  • 19