- Home
- /
- Tutorials
- /
- React Tutorial
- /
- Showing, Hiding and Losing State
Conditional Rendering
Showing, Hiding and Losing State
A component that stops being rendered is unmounted, and its state is thrown away. Hiding it with CSS keeps it alive. That difference is invisible until it bites.
Not rendered means gone
When a condition turns false, React removes the component from the tree. Its state, and anything it was holding, is discarded - bringing it back gives you a fresh component with its initial value.
State does not survive unmounting
jsx
function Counter({ label }) {
const [count, setCount] = React.useState(0)
return (
<button onClick={() => setCount(count + 1)}>
{label}: {count}
</button>
)
}
function Demo() {
const [show, setShow] = React.useState(true)
return (
<div>
<button onClick={() => setShow((s) => !s)}>
{show ? "Hide" : "Show"} the counters
</button>
<div style={{ marginTop: 10, display: "flex", gap: 8 }}>
{/* Unmounted when hidden — the count resets. */}
{show && <Counter label="Removed" />}
{/* Always mounted, just invisible — the count is kept. */}
<div style={{ display: show ? "block" : "none" }}>
<Counter label="Hidden with CSS" />
</div>
</div>
<p style={{ color: "#64748b" }}>
Click each counter up, hide, then show. Only the second remembers.
</p>
</div>
)
}
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(<Demo />)