React, useRef Gotchas
useRef
is like a “box” or a "container" that can hold a mutable value in its .current
property.
1) Manipulate the DOM
useRef
is used mostly for ref
attribute. <div ref={myRef} />
, React will set its .current
property to the corresponding DOM node whenever that node changes.
2) Contain a mutable value
It’s also handy for keeping any mutable value similar to how you’d use instance fields in classes.
useRef
can store the values between re-renders. A variable will lose the reference between renders and will reset on every render.
useRef
doesn’t notify you when its content changes. Mutating the.current
property doesn’t cause a re-render. Rendering should be handled manually by the consumer of theuseRef
.