Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

408
Views
Why should I use refs in React when I can perform the operation using getElementById?

I was reading the docs Refs and the DOM and A complete guide to React refs to better understand the concept of refs in React. However, I am not sure why the concept is needed when it can be solved in the vanilla JS way.

For example, in the 2nd link mentioned above, the author of the article says that React does not provide an easy way to auto-focus a text element and that in such a scenario, refs would come in handy. To check that, I was experimenting with alternative methods to achieve the same auto-focus without refs. Here is a part of my solution:

class ExampleComponent extends Component {
  .
  .
  .
  componentDidMount () {
    // accessing an element without using refs
    const element = document.getElementById(this.inputId);

    if (element) {
      element.focus();
    }
  }
  .
  .
  .
  render () {
    return (
      <input id={this.inputId} onChange={this.handleChange} value={this.state.value} />
    );
  }
}

And it works.

How are refs better than the solution above? It seems pretty simple to me but I might be missing out on something.

Thanks in advance.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!