score:-1

in general, if you declare a simple javascript variable yourself, it will be updated on each render. refs are used when you need to persist some value during re-renders, actually it will give you the same ref object on every render.

but in this case, you've moved the variable outside the component, and used it inside the component, if you want to change it, it will break the functional programming rules (pure functions)

score:3

react.useref(0) is part of the component life-cycle. if you render two different app in your application, those two ref won't collide. they will if you refer to the same shared and mutable variable, like in your second example. you will have a situation where one instance of app will have unintended side effects to the second instance of app.

score:4

i think that the difference is about the component packaging and exporting. let's say you import app from the file, this doesn't mean the whole file is exported, this is a module, only the exported app component gets exported. so when you use ref, you have the access to a persistent variable without going outside of the component scope, so you can still use it when exporting.

also how would you differentiate between multiple instances of the app component that might need a different value with the same variable? useref() automatically distinguishes those.


Related Query

More Query from same tag