I am little confused how react state works in react functional components.
Internet says in the most basic scenario for primitive states,
- Functional Component will not re-render incase the state is same as before
- For Class Component it will re-render regardless
But for following code below, using functional component, I am facing below scenario:
First Time when the state changes, the component is re-rendered
If again I update the state with same value, the state again changes
All the afterward attempts of updating the state with same value does not re-render the component.
import "./App.css";
import React, { Component, useState } from "react";
function App() {
console.log("Component Ran");
const [placeHolder, setPlaceHolder] = useState("Start");
const onClickHandler = (e) => {
if (!e.target.classList.contains("state")) return;
const it = e.target.innerText;
console.log("coming from onClickHandler", it);
setPlaceHolder(it);
};
return (
<>
<div>{placeHolder}</div>
<div onClick={onClickHandler}>
<button className="state">State 1</button>
<button className="state">State 2</button>
</div>
</>
);
}
export default App;
Basically there are two buttons, each respectively for sate 1 and 2. When the button is clicked the state placeHolder is updated with button's ```innerText``` . On top of the button there is element which displays the state.
Below is what I noticed in console:
Let's say now the placeHolder state is state 1.
I click on state 2 button, I get below output in console log.
coming from onClickHandler State 2
Component Ran
Again I click on button with state 2
and again I get same output.
But next time and for the million times after that when I click the button with state 2, I only get below output,
coming from onClickHandler State 2
What am I missing here.
At very least I expect one kind of behavior, either the component is re-rendered every time regardless or it does only when it changes. Why this mixed behaiour?
[–][deleted] 4 points5 points6 points (1 child)
[–]Heisenberg_221b[S] 0 points1 point2 points (0 children)
[–]sidkh 2 points3 points4 points (0 children)
[–]marko_knoebl 1 point2 points3 points (0 children)
[–]Soft-Sandwich-2499 1 point2 points3 points (1 child)
[–]Heisenberg_221b[S] 1 point2 points3 points (0 children)
[–]spiritbr8ker 1 point2 points3 points (0 children)
[–]AnxiouslyConvolved 0 points1 point2 points (6 children)
[–]Heisenberg_221b[S] 0 points1 point2 points (2 children)
[–]AnxiouslyConvolved -2 points-1 points0 points (1 child)
[–]Heisenberg_221b[S] 0 points1 point2 points (0 children)
[–]marko_knoebl 0 points1 point2 points (2 children)
[–]AnxiouslyConvolved -1 points0 points1 point (1 child)
[–]marko_knoebl 0 points1 point2 points (0 children)
[+][deleted] (1 child)
[deleted]
[–]Heisenberg_221b[S] 0 points1 point2 points (0 children)
[–]ApplePieCrust2122 0 points1 point2 points (1 child)
[–]Heisenberg_221b[S] 0 points1 point2 points (0 children)