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
I would say the most impactful difference between a ref and a file-scoped variable is:
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.
In your case, you don’t need to use an external variable, or a ref.
useEffect
is a closure, and unless the dependencies ofuseEffect
change, the closure will maintain the variable values: