title: "useRefs" variable an initial value of a div reference?
body: <p>Im trying to build an audio progess bar with react hooks. I was following a tutorial with react class based components but got a little lost with refs. </p>
  
  <p>How can I give my useRef variables an initial value of the div ref when the page loads?</p>
  
  <p>As soon as I start playing then the I get an error saying cant read offsetwidth of null. Obviously timeline ref is null as it doesnt have an initial value. How can I connect it to the div with id of timeline in the useEffect hook? </p>
  
  <pre><code>const AudioPlayer = () =&gt; {
    const url = "audio file";
  
    const [audio] = useState(new Audio(url));
    const [duration, setDuration] = useState(0);
    const [currentTime, setCurrentTime] = useState(0)
    let timelineRef = useRef()
    let handleRef = useRef()
  
    useEffect(() =&gt; {
      audio.addEventListener('timeupdate', e =&gt; {
        setDuration(e.target.duration);
        setCurrentTime(e.target.currentTime)
        let ratio = audio.currentTime / audio.duration;
        let position = timelineRef.offsetWidth * ratio;
        positionHandle(position);
      })
    }, [audio, setCurrentTime, setDuration]);
  
  
  
    const mouseMove = (e) =&gt; {
      positionHandle(e.pageX);
      audio.currentTime = (e.pageX / timelineRef.offsetWidth) * audio.duration;
    };
  
    const mouseDown = (e) =&gt; {
      window.addEventListener('mousemove', mouseMove);
      window.addEventListener('mouseup', mouseUp);
    };
  
    const mouseUp = (e) =&gt; {
      window.removeEventListener('mousemove', mouseMove);
      window.removeEventListener('mouseup', mouseUp);
    };
  
    const positionHandle = (position) =&gt; {
      let timelineWidth = timelineRef.offsetWidth - handleRef.offsetWidth;
      let handleLeft = position - timelineRef.offsetLeft;
      if (handleLeft &gt;= 0 &amp;&amp; handleLeft &lt;= timelineWidth) {
        handleRef.style.marginLeft = handleLeft + "px";
      }
      if (handleLeft &lt; 0) {
        handleRef.style.marginLeft = "0px";
      }
      if (handleLeft &gt; timelineWidth) {
        handleRef.style.marginLeft = timelineWidth + "px";
      }
    };
  
  
    return (
      &lt;div&gt;
  
        &lt;div id="timeline" ref={(timeline) =&gt; { timelineRef = timeline  }}&gt;
        &lt;div id="handle" onMouseDown={mouseDown} ref={(handle) =&gt; { handleRef = handle }} /&gt;
        &lt;/div&gt;
      &lt;/div&gt; 
    )
  }
  </code></pre>