skip to Main Content

Trying to use useRef hook on a functional component. I’m getting: {current: null} when I try to log this to console. Any thing look off here?


import React, {useRef} from 'react';

const Hi = () => (

const span = useRef<HTMLSpanElement>(null);
console.log(span);

return(
  <div>
    <p>hi</p>
  </div>
)
);

export default Hi;

2

Answers


  1. useRef doesn’t create an HTML element; rather, you need to attach the resulting reference to an appropriate JSX element (by writing e.g. <span ref={span} />), and React will then update the reference to point to the relevant element node or component.

    This means two things:

    1. You need to include the appropriate JSX element in the return-value of your component function.
    2. Even once you’ve done that, you can’t really use the ref inside the component function itself (at least the first time it’s called), because the element node won’t have been created yet. Rather, the ref is available for use in event handlers and effects and so on.

    For more information, see https://react.dev/reference/react/useRef#manipulating-the-dom-with-a-ref

    Login or Signup to reply.
  2.  const pRef = useRef(null);
    
      useEffect(() => {
        console.log(pRef.current);
      }, []);
    
      return <p ref={pRef}>hi</p>;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search