React: Property `current` of `ref`

Created on 10 Apr 2018  路  5Comments  路  Source: facebook/react

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?

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.

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 })

All 5 comments

@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.

Was this page helpful?
0 / 5 - 0 ratings