1

Having such a simple React App:

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

import "./styles.css";

function App() {

  console.log("App")

  const [inputValue, setInputValue] = useState(0);

  return (
    <>
      <input
        type="text"
        onChange={(e) => setInputValue("e.target.value")}
      />
      <button onClick={(e) => setInputValue(1)}>
        Click me
      </button>
      <h1>Render Count: {inputValue}</h1>
    </>
  );
}

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

I'm getting initially (after the App loads):

App

AND

App

App

on interaction - when I click the button or type sth. in the input field.

My question is WHY does the App is printed TWICE in the second case (interaction)!? It's strange because the inputValue is ONLY changed ONCE on the first click/input but in the second interaction it stays the same, not changing anymore!

P.S.

It's NOT the case of the react strict mode! - In the index.js I have:

...
ReactDOM.render(<App />, rootElement);
...

so I'm NOT using react strict mode!

darro911
  • 136
  • 6
  • 1
    One issue: `setInputValue("e.target.value")` should not be in double quotes. Here is a exact replica of your code on codesandbox - https://codesandbox.io/s/awesome-fog-jmrsiv?file=/src/index.js I can't reproduce two renders. – A G May 05 '22 at 10:09
  • When I try out the example in a codesandbox, I get one console.log when I type a character into the input and a second one when I click the button. That looks absolutely correct to me. Is it different for you? If not, which of the two console.logs do you find confusing? – Giraphi May 05 '22 at 10:22

2 Answers2

0

When the component mounts, there is always one render. Then when the state changes from 0 -> 1 there is another render.

When using the useState hook, it re-renders whenever a state value changes, not necessarily every time you call setState (which was the old behaviour). So every time you click after the first time, the state goes from 1 -> 1 and you get no re render because the value is the same.

rymanso
  • 869
  • 1
  • 9
  • 21
0

React setState causes re-render.

You can learn more about this behavior here: How does React.useState triggers re-render?