Cleaning a Dirty State

Good evening,

I am wondering what the best way to clean a state which

  1. I want to manipulate in another section of the page
  2. 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>
  );
};

I was thinking of making a new a new function to manipulate a value that the user sees and another that would be affected, but I felt that would be messier (as well as making another useState).

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.