I was puzzled when using property current
to access ref
of DOM or component, current
is the only property that I can access in ref
object, what is the purpose of this property?
this.inputRef.current.focus()
this.inputRef.focus() // Isn't this a better way to use ref?
@TrySound But what is the benefit of doing so? Some performance concern?
@liril-net No. You pass your ref to the component. The component need to update this ref. With this case it's not possible.
const component = ({ ref }) => {
ref = new Element
}
const ref = null
component({ ref })
That's why createRef is object with mutable field, which can be updated by component.
const component = ({ ref }) => {
ref.current = new Element
}
const ref = { current: null }
component({ ref })
Thanks for your reply.
To be clear React itself will set the current
property. Not a component.
Most helpful comment
@liril-net No. You pass your ref to the component. The component need to update this ref. With this case it's not possible.
That's why createRef is object with mutable field, which can be updated by component.