I'm new to React. Here I'm trying to add/remove a 'Timer' component on click of +/- button. It works fine on click of '+', but not on '-'. I was of the opinion that every time I set a state, the component re-renders. But here it doesn't render on click of '-' button.
- What might be going wrong here?
- Also any better approach to do the same is welcome.
function App() {
var [timers, setTimers] = useState([]);
var [count, setCount] = useState(0);
const addTimer = () => {
setCount(count + 1);
timers.push(count);
setTimers(timers);
console.log(timers); //[0]
};
const removeTimer = () => {
timers.pop();
setTimers(timers);
console.log(timers); //[]
};
return (
<div>
<button className="button" onClick={addTimer}>
+
</button>
<button className="button" onClick={removeTimer}>
-
</button>
<div>
{timers.map((t) => (
<Timer key={t} />
))}
</div>
</div>
);
}