Two counters switch style: which one keeps its count?
Counter A switches style with a ternary. Counter B switches with two && conditions. You add to each twice, then switch the style.
import { useState } from "react";
function Counter({ label, fancy }) {
const [count, setCount] = useState(0);
return (
<p className={fancy ? "fancy" : ""}>
{label}: {count} <button onClick={() => setCount(count + 1)}>Add to {label}</button>
</p>
);
}
export default function App() {
const [fancy, setFancy] = useState(false);
return (
<>
<div>{fancy ? <Counter label="A" fancy /> : <Counter label="A" />}</div>
<div>
{fancy && <Counter label="B" fancy />}
{!fancy && <Counter label="B" />}
</div>
<button onClick={() => setFancy(!fancy)}>Switch style</button>
</>
);
}
It runs in development, rendered as <App />, and then:
- You click Add to A twice.
- You click Add to B twice.
- You click Switch style.
The answer
Work out every line it logs, in order, and what the page shows at the end. Then check.
Checking your sign-in…