theMobDog
theMobDog

Reputation: 1389

Why shouldn't we use ref?

In Facebook's documentation on refs:

Don’t Overuse Refs Your first inclination may be to use refs to “make things happen” in your app. If this is the case, take a moment and think more critically about where state should be owned in the component hierarchy. Often, it becomes clear that the proper place to “own” that state is at a higher level in the hierarchy. See the Lifting State Up guide for examples of this.

In my current React app, I have a few div nodes that I want to modify on condition. Those div nodes were created deep inside the render()'s chained returns. I certainly can't use Document.queryselector(). And I cannot think of anything else.

Documentation also tried to explain with article "lifting state up" but I didn't understand. Can someone shed a light on this one? (ELI5 if you could.)

Upvotes: 2

Views: 4570

Answers (1)

Andy Gaskell
Andy Gaskell

Reputation: 31761

Lifting state means that child components raise events instead of handling state changes themselves. In the React docs they start off with each component managing its own state (handleChange). Further down they lift state up by adding the onTemperatureChange prop. Now the children delegate the state change to their closest common parent, Calculator. Calculator changes state and pushes the new values down through props.

I use refs only when I need to call specific functions on DOM elements, with focus() being by far the most common usage in my applications. This SO answer has a good example, copied here because links are bad:

class App extends React.Component{
  componentDidMount(){
    this.nameInput.focus();
  }
  render() {
    return(
      <div>
        <input 
          defaultValue="Won't focus" 
        />
        <input 
          ref={(input) => { this.nameInput = input; }} 
          defaultValue="will focus"
        />
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));

Also be sure to read the answer below the linked answer, autoFocus is the correct answer for focusing when mounted but there are for sure times where you want to focus elements dynamically.

Upvotes: 1

Related Questions