skip to Main Content

I am using the UseRef hook to create a Ref variable and inserting that into one of the components in my return statement. ‘AnimationComponent’ has it’s own <g></g> tags which return some inner elements.

The basic outline of my code is like this:

var refVar1 = useRef();

useEffect(()=>{
    console.log("value of refVar1 : " + refVar1);
    console.log("value of refVar1.current : " + refVar1.current);
}, [])


return(
  <g>
     <path>
        <AnimationComponent ref={refVar1}>
     </path>
  </g>
)

I’m finding that the value of refVar1 and refVar1.current are always undefined.

Which makes me wonder what how is the code really flowing in React? Once ‘AnimationComponent’ is rendered, does that mean that the code within the useEffect will never execute afterwards?

I always thought all the code in React components is " asynchronous " in a way. Even when inner children components are rendered, the code in the parents will still execute simultaneously?

I have tried putting those console log statements inside UseEffects and outside them. They always show as undefined.

Edit: Sorry, it’s only refVar1.current that shows up as undefined. refVar1 shows up as ‘ [object object] ‘ on the console.

2

Answers


  1. Your code should be executed when useRef != undefined. useEffect will listen to refVar.current, so when refVar1 is defined your logic will be executed again.

        var refVar1 = useRef();
        
        useEffect(()=>{
            if(gridInstance.current){
                console.log("value of refVar1 : " + refVar1);
                console.log("value of refVar1.current : " + refVar1.current);
            }
        }, [refVar1.current])
        
        
        return(
          <g>
             <path>
                <AnimationComponent ref={refVar1}>
             </path>
          </g>
        )
    
    Login or Signup to reply.
  2. You need to use forwardRef to pass the reference. Here is an example:

    Created a simple component which is receiving ref

    import { forwardRef } from "react";
    
    const MyComp = forwardRef((props, ref) => {
      return (
        <div ref={ref}>
          <h1>Hello World</h1>
        </div>
      );
    });
    
    export default MyComp;
    

    Parent component

    import { useRef, useEffect } from "react";
    import MyComp from "./myComp";
    
    export default function App() {
      const refVar1 = useRef();
      useEffect(() => {
        console.log("value of refVar1 : ", refVar1);
        console.log("value of refVar1.current : ", refVar1.current);
      }),
        [];
    
      return (
        <div >
          <MyComp ref={refVar1} />
        </div>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search