I have a component, I set a count and let state update when button clicked. But when I check render times, it renders twice each time I click the button.
https://codesandbox.io/s/brave-forest-yre6y?file=/src/App.js
export default function App() {
const cute = Array(10).fill({});
const [count, setCount] = useState(2);
console.log(count);
return (
<div className="App">
<button
onClick={() => {
if (count < 10) setCount(count + 1);
}}
>
add
</button>
{cute.map((data, index) => {
if (index < count) {
return (
<div>
<p>{index}. Luna is cute</p>
</div>
);
}
})}
</div>
);
}
I wonder:
- Why does it work like this?
- How could I prevent this?