React Refs

Refs provide a way to access DOM nodes or React elements created in the render method. It is used when we want to change the value of a child component, without making the use of props

When to Use Refs?

There are a few use cases for refs:

1.Managing focus, text selection, or media playback.
2.Triggering imperative animations.
3.Integrating with third-party DOM libraries.

when not to use refs?

1.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.
2.You should have to avoid overuse of the Refs.

How to create ref?

1.Refs are created using React.createRef() and attached to React elements via the ref attribute.
2.Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.

class MyComponent extends React.Component {
  constructor(props) {
    this.myRef = React.createRef();
  render() {
    return <div ref={this.myRef} />;

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. So we can use ref using its current value.

const node = this.myRef.current;

Refs current Properties:

The ref value differs depending on the type of the node:
1.When the ref attribute is used in the HTML element, the ref created with React.createRef() receives the underlying DOM element as its current property.
2.If the ref attribute is used on a custom class component, then ref object receives the mounted instance of the component as its current property.
3.The ref attribute cannot be used on function components because they don’t have instances.