Refs in React are used to access DOM nodes or React elements directly within components. It is often used for managing focus, text selection, or media playback.
A basic usage of ref is as shown below:
```
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
Here, constructor initializes this.myRef to hold a React ref, and we then attach it to an element in the render function via the ref attribute.
Once a ref is attached to an element, the ref can be used to access the properties of that element. If we wanted to imperatively change the value of the above div, we could do so with this line of code:
```
this.myRef.current.innerHTML = ‘New value’;
```
Current is the React property that holds the value of the ref.
It’s important to note that changing props and state in React often leads to a re-render of components, whereas changes made with refs may not. Therefore, React’s official recommendation is to avoid using refs for anything that can be done declaratively.
For example, instead of using ref to read a value, use props and state. However, there are a few good use cases for refs such as managing focus, text selection, media playback.
Another caution is that it should not be overused since if it’s used excessively it might make the application harder to understand, since data flow throughout the components will become harder to track and understand.
Use cases for refs:
1. Managing focus, text selection, or media playback.
2. Triggering imperative animations.
3. Integrating with third-party DOM libraries.