source: https://medium.com/@rossbulat/how-to-use-react-refs-4541a7501663

React Refs are a useful feature that act as a means to reference a DOM element or a class component from within a parent component. This then give us a means to read and modify that element.

Using refs give us a way to access elements while bypassing state updates and re-renders; this can be useful in some use cases, but should not be used as an alternative to props and state.

Refs also provide some flexibility for referencing elements within a child component from a parent component, in the form of ref forwarding.

Refs at a high level

Refs are usually defined in the constructor of class components, or as variables at the top level of functional components, and then attached to an element in the render() function. Here is a bare-bones example where we are creating a ref and attaching it to an <input> element:

class MyComponent extends React.Component {
constructor(props) {
super(props)
this.myRef = React.createRef();
} ...
render() {
return (
<>
<input
name="email"
onChange={this.onChange}
ref={this.myRef}
type="text"
</>
)
}
}

Refs are created using React.createRef(), and are assigned to class properties. In the above example the ref is named myRef, which is then attached to an <input> DOM element.

Once a ref is attached to an element, that element can then be accessed and modified through the ref.

Let’s add a button to our example. We can then attach an onClick handler that will utilise myRef to focus the <input> element it is attached to:

...handleClick = () => {
this.myRef.current.focus();
}render() {
return (
...

<button onClick={this.handleClick}>
Focus Email Input
</button>
</>
)
}

By doing this we are in fact changing the state of an input element without any React state updates. This makes sense in the case of focussing an <input>— we wouldn’t want to re-render elements every time we focus / blur an input. There are a few more cases where refs make sense; we will visit those further down the article.

At the componentDidMount lifecycle stage, myRef.current will as expected be assigned to our <input> element; componentDidMount is generally a safe place to process some initial setup with refs, e.g. focussing the first input field in a form as it is mounted on stage.

What if we change componentDidMount to componentWillMount? Well, myRef will be null at this stage of the component lifecycle. Refs will be initialised after the component mounts, whereby the elements we are attaching refs to need to be mounted (or rendered) on the stage. Therefore, componentWillMount is not suitable for accessing refs.

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.