FOLASAYO SAMUEL OLAYEMI
SV_D_CURIOUS_SOFTWARE_ENGINEER'S BLOG

SV_D_CURIOUS_SOFTWARE_ENGINEER'S BLOG

What are refs in React? When should they be used?

FOLASAYO SAMUEL OLAYEMI's photo
FOLASAYO SAMUEL OLAYEMI
·Apr 29, 2022·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Refs provide a way to access DOM nodes or React elements created in the render method. Refs should be used sparingly, but there are some good use cases for refs, such as:

  • Managing focus, text selection, or media playback.

  • Triggering imperative animations.

  • Integrating with third-party DOM libraries.

Refs are created using React.createRef() method and attached to React elements via the ref attribute. In order to use refs throughout the component, assign the ref to the instance property within the constructor.

Code Sample:

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
    this.myRef = React.createRef()
  }

  render() {
    return <div ref={this.myRef} />
  }
}
  • Refs can also be used in functional components with the help of closures.
  • Refs are used to return a reference to an element.
  • Refs shouldn't be overused.

You can create a ref using React.createRef() and attach to elements via the ref attribute.

Note: Avoid using refs for anything that can be done declaratively.

For example, instead of exposing open() and close() methods on a Dialog component, pass an isOpen prop to it.

How to access Refs

When a ref is passed to an element in render, a reference to the node becomes accessible at the current attribute of the ref.

const node = this.myRef.current;

Read More

Thanks for reading...

Happy Coding!

 
Share this