title: When to use useEffect without dependencies vs. direct assignment?
body: <p>I am writing a React hook that allows me to use <code>setInterval</code> in my components. In order to do so I need to keep the latest version of the callback in a ref so that it can be accessed from the scope of the interval later on.</p>
  <p>This is my code so far:</p>
  <pre><code>import { useRef, useEffect } from 'react'
  
  export default function useInterval(
    callback: () =&gt; void,
    delay: number | null,
  ) {
    const callbackRef = useRef(callback)
  
    // Remember the latest callback.
    useEffect(() =&gt; {
      callbackRef.current = callback
    })
  
    useEffect(() =&gt; {
      // Don't schedule if no delay is specified.
      if (delay === null) {
        return
      }
  
      const id = setInterval(() =&gt; callbackRef.current(), delay)
  
      return () =&gt; clearInterval(id)
    }, [delay])
  }
  </code></pre>
  <p>My question is about the first instance of <code>useEffect</code> where the latest value is passed to the ref. According the the React documentation this code will execute after my component has rendered.</p>
  <p>I can imagine this is useful when you are passing a ref to an element so you can be sure that it has a value after it has rendered. But if my code doesn't care about when the component renders, does it still make sense to keep this in a <code>useEffect</code>?</p>
  <p>Would it make sense that I rewrite the code as follows:</p>
  <pre><code>import { useRef, useEffect } from 'react'
  
  export default function useInterval(
    callback: () =&gt; void,
    delay: number | null,
  ) {
    const callbackRef = useRef(callback)
  
    // Remember the latest callback.
    callbackRef.current = callback
  
    useEffect(() =&gt; {
      // Don't schedule if no delay is specified.
      if (delay === null) {
        return
      }
  
      const id = setInterval(() =&gt; callbackRef.current(), delay)
  
      return () =&gt; clearInterval(id)
    }, [delay])
  }
  </code></pre>