Reputation: 466
The useRef
documentation says it is handy for keeping any mutable value around. I was wondering why we can't just use a variable in the outer scope of the component for that purpose?
// the object I want to keep around
let obj;
function MyComponent() {
useEffect(() => {
obj = //some code
}, []);
return (...)
}
It works, doesn't it? So why exactly is useRef
better?
Upvotes: 0
Views: 56
Reputation: 1625
The variable in the outer scope is shared between instances of your component. useRef
will create a mutable object local to your component (and it will stay around as long as your component is mounted).
Upvotes: 2