Good evening,
I am wondering what the best way to clean a state which
- I want to manipulate in another section of the page
- See what the original state is, no matter if I manipulated it at another part.
Here is the code:
const { useState, useEffect } = React;
const App = () => {
const [isPlaying, setIsPlaying] = useState(false);
const [specialNum, setSpecialNum] = useState(5);
useEffect(() => {
const interval = setInterval(() => {
if (isPlaying) {
if (specialNum > 0) {
setSpecialNum(specialNum - 1);
}
} //if isPlaying
}, 1000);
return () => clearInterval(interval);
});
const restartFunc = () => {
setIsPlaying(false);
setSpecialNum(specialNum);
};
return (
<div>
{/*Original special number is ALWAYS displayed, even when isPlaying is true*/}
<h1>Special Num: {specialNum}</h1>
<h1>Seconds from this going to zero: {specialNum}</h1>
<button onClick={() => setSpecialNum(specialNum + 1)}>
Increase Special Num
</button>
<button onClick={() => setIsPlaying(true)}>Start Count Down</button>
{/*Original special number is displayed when I restart*/}
<button onClick={() => restartFunc()}>Restart</button>
</div>
);
};