Reputation: 57
For example, I have a state and it can be changed by clicking on the buttons. I also have a log to track the rendering and rerendering of the component. When I click on the button and change the state, the log is triggered and everything is fine. But when I click 2 times on the same value, the log fires again. Clicking 3 times does nothing. Please explain what could be the reason
const App = () => {
const [state, setState] = useState(1);
console.log("render");
return (
<div>
<h3>{state}</h3>
<button onClick={() => {setState(1)}}>1</button>
<button onClick={() => {setState(2)}}>2</button>
</div>
);
};
export default App;
Upvotes: 0
Views: 32
Reputation: 130
React rerenders a component if the state is changing, but in your example, when you click on a button again, the value of state does not change, because you want to change value of 2 to 2, so react does not rerender the component.
Upvotes: 2