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
!
CodePudding user response:
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.
CodePudding user response:
React setState causes re-render.
You can learn more about this behavior here: How does React.useState triggers re-render?