title: Why does focusing a textarea not work without a setTimeout of 0?
body: <p>I have a button to edit a div which turns it into a textarea. I use this code because I want the cursor to appear at the end of the textarea after I begin editing:</p>
  
  <pre><code>constructor(props) {
    super(props);
  
     this.state = { body: "asdf" };
  
    this.messageItemRef = React.createRef();
  }
  
  componentDidMount() {
    let length = this.state.body.length;
  
    setTimeout(() =&gt; {
      this.messageItemRef.current.focus();
      this.messageItemRef.current.setSelectionRange(length, length);
    }, 0);
  }
  
  
  render() {
    return ( 
      &lt;textarea ref={this.messageItemRef} value={this.state.body} /&gt;
    );
  }
  </code></pre>
  
  <p>I randomly decided to try the <code>setTimeout</code> of 0 after it was only working when I clicked the edit button and not when I used a hotkey to edit it.</p>
  
  <p>I'm wondering, why is the setTimeout of 0 needed? If I get rid of it, it only focuses the end of the textarea when I click the button, and not when I use the keyboard hotkey.</p>
  
  <p>Why is this?</p>