skip to Main Content

From the Hooks FAQ in the old (and no longer updated) React documentation:

Is there something like instance variables?

Yes! The useRef() Hook isn’t just for DOM refs. The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class.

You can write to it from inside useEffect:

function Timer() {
  const intervalRef = useRef();
  useEffect(() => {
   const id = setInterval(() => {
     // ...
   });
   intervalRef.current = id;    return () => {
     clearInterval(intervalRef.current);
   };
 });

 // ...
}

In the new documentation a similar example is given.

Are there any alternatives?

Can’t you just define a variable outside of the component, which is accessible in this scope? What are the downsides of the latter approach, aside from obviously introducing a file-scoped global variable?

2

Answers


  1. I would say the most impactful difference between a ref and a file-scoped variable is:

    By using a ref, you ensure that:

    • The information is local to each copy of your component (unlike the variables outside, which are shared).

    Source: React Docs (Emphasis mine)

    So, for components that aren’t reused there may not be any noticeable difference, but for anything that appears multiple times on a page, refs are the safe approach to avoid cross-contamination.

    Login or Signup to reply.
  2. In your case, you don’t need to use an external variable, or a ref. useEffect is a closure, and unless the dependencies of useEffect change, the closure will maintain the variable values:

    function Timer() {
      useEffect(() => {
        const id = setInterval(() => {
          // ...
        });
    
        return () => {
          clearInterval(id);
        };
      }, []); // use an empty dependencies array
    
      // ...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search