What's a bad practice with refs in React?

Krizzu picture Krizzu · Nov 12, 2016 · Viewed 8k times · Source

I'm getting to learn React. Some guys of different sites tells everyone that using refs is a bad practice (yep, using them at all).

What's the real deal with it? Is it something bad that I will attach it to, for example, child component (so I can access inner stuff)?

Thanks!

Answer

skav picture skav · Nov 13, 2016

React requires you to think the react way and refs are kind of a backdoor to the DOM that you almost never need to use. To simplify drastically, the react way of thinking is that once state changes, you re-render all the components of your UI that depend on that state. React will take care of making sure only the right bits of the DOM are updated, making the whole thing efficient and hiding the DOM from you (kinda).

For example, if your component hosts an HTMLInputElement, in React you'll wire up an event handler to track changes to the input element. Whenever the user types a character, the event handler will fire and in your handler you'll update your state with the new value of the input element. The change to the state triggers the hosting component to re-render itself, including the input element with the new value.

Here's what I mean

import React from 'react';
import ReactDOM from 'react-dom';

class Example extends React.Component {

    state = {
      inputValue: ""
    }

    handleChange = (e) => {
      this.setState({
        inputValue: e.target.value
      })
    }

    render() {
        const { inputValue } = this.state
        return ( 
          <div>
            /**.. lots of awesome ui **/
            /** an input element **/
            <input value={inputValue} onChange={this.handleChange}} />
            /** ... some more awesome ui **/
          </div>
       )
  }
}


ReactDOM.render( <Example />, document.getElementById("app") );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>


<div id="app">
</div>

Notice how anytime the input value changes, the handler gets called, setState gets called and the componet will re-render itself in full.

Its generally bad practice to think about refs because you might get tempted to just use refs and and do things say the JQuery way, which is not the intention of the React architecture/mindset.

The best way to really understand it better is to build more React apps & components.