I have a simple functional component with a boolean state. And buttons to change the state.
It is initially set to true
so when I press the true-button, it does NOT render.
But if I press the false-button, it re-renders AND if I press false-button AGAIN, it will re-render even though the state is already set to false
..
Could someone explain why the component re-renders when the state changes to the exact same state? How to prevent it from re-rendering?
import React, {useState} from 'react';
const TestHooks = () => {
const [state, setState] = useState(true);
console.log("rendering..", state);
return(
<div>
<h1>{state.toString()}</h1>
<button onClick={() => setState(true)}>true</button>
<button onClick={() => setState(false)}>false</button>
</div>
)
}
export default TestHooks;
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…