React Hooks: Why is .current null for useRef Hook?

Ref.current is null because the ref is not set till after the function returns and the content is rendered. The useEffect hook fires every time the value of contents of the array passed to it changes. By passing observed in the array and by passing a callback that logs observed to the console, the useEffect hook can be leveraged to accomplish your task.

  useEffect(() => {
    console.log(observed.current);
  }, [observed]);

Edit: This only works on the first render as changes to a ref do not trigger re-renders. But the general statement about useEffect still holds. If you want to observe changes to a ref of a dom element, you can use a callback as ref.

  <div 
    ref={el => { console.log(el); observed.current = el; }} // or setState(el)
    className="App"
  >

Code Sandbox

Leave a Comment