title: React: useState or useRef?
body: <p>I am reading about React <code>useState()</code> and <code>useRef()</code> at  &quot;<a href="https://reactjs.org/docs/hooks-faq.html" rel="noreferrer">Hooks FAQ</a>&quot; and I got confused about some of the use cases that seem to have a solution with useRef and useState at the same time, and I'm not sure which way it the right way.</p>
  <p>From the &quot;Hooks FAQ&quot; <a href="https://reactjs.org/docs/hooks-faq.html#is-there-something-like-instance-variables" rel="noreferrer">about useRef()</a>:</p>
  <blockquote>
  <p>&quot;The useRef() Hook isn’t just for DOM refs. The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class.&quot;</p>
  </blockquote>
  <p>With <strong>useRef()</strong>:</p>
  <pre><code>function Timer() {
    const intervalRef = useRef();
  
    useEffect(() =&gt; {
      const id = setInterval(() =&gt; {
        // ...
      });
      intervalRef.current = id;
      return () =&gt; {
        clearInterval(intervalRef.current);
      };
    });
  
    // ...
  }
  </code></pre>
  <p>With <strong>useState()</strong>:</p>
  <pre><code>function Timer() {
    const [intervalId, setIntervalId] = useState(null);
  
    useEffect(() =&gt; {
      const id = setInterval(() =&gt; {
        // ...
      });
      setIntervalId(id);
      return () =&gt; {
        clearInterval(intervalId);
      };
    });
  
    // ...
  }
  </code></pre>
  <p>Both examples will have the same result, but which one it better - and why?</p>