DEV Community

Cover image for Day 9 - What is ref in react?
C K Sanjay Babu
C K Sanjay Babu

Posted on • Originally published at on


Day 9 - What is ref in react?

In react, Refs provide a way to access or reference the DOM element from within a parent component. Generally, in react, we would use props for any interactions between the components. We can re-render the component with updated props to modify it. Refs provide a way to imperatively do this change.

When to use Refs?

According to react documentation,

  • Manage focus, text selection, or media playback.
  • Perform imperative animations.
  • Integrate with third-party DOM libraries.

When not to use Refs?

We use a library like react for its declarative programming style. We just specify this or that needs to be done and the react handles it. But when the ref provides us the flexibility of imperative control. Hence these should not be overused.


class CustomTextInput extends React.Component {
  constructor(props) {
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
          ref={this.textInput} />
          value="Focus the text input"

Enter fullscreen mode Exit fullscreen mode

Top comments (2)

andrewbaisden profile image
Andrew Baisden

Refs are so useful they have solved so many problems for me in the past when working on React projects.

sanjaybabu profile image
C K Sanjay Babu • Edited

Refs saved my day once when I was working with animations, other than havent used it much personally!
But they surely are really useful in few peculiar cases.

Super Useful CSS Resources

A collection of 70 hand-picked, web-based tools which are actually useful.
Each will generate pure CSS without the need for JS or any external libraries.