Using refs with conditional rendering

TL;DR:

Change this:

this.setState({isEditing: !this.state.isEditing})
this.textInput.current.focus();

to this:

this.setState(previousState => ({isEditing: !previousState.isEditing}), () => {
    this.textInput.current.focus();    
});

Update: Functional Components / Hooks

It's been asked in the comments how to do this with useState and functional components. Rafał Guźniczak's answer explains it, but I wanted to provide a bit more explanation and a runnable example.

You still don't want to read state immediately after setting it, but instead of using a second argument callback to setState, you need to run some code after the state is updated and the component has re-rendered. How do we do that?

The answer is useEffect. The purpose of effects are to synchronize external "things" (for example: imperative DOM things like focus) with React state:

const { useEffect, useRef, useState } = React;
const { render } = ReactDOM;

function App(props) {
  const [isEditing, setIsEditing] = useState(false);
  const textInputRef = useRef(null);

  const toggleEditing = () => setIsEditing(val => !val);

  // whenever isEditing gets set to true, focus the textbox
  useEffect(() => {
    if (isEditing && textInputRef.current) {
      textInputRef.current.focus();
    }
  }, [isEditing, textInputRef]);

  return (
    <div>
      <button onClick={toggleEditing}>lorem </button>
      {isEditing && <input type="text" ref={textInputRef} />}
    </div>
  );
}

render(
  <App />,
  document.getElementById('root')
);
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>

<div id="root"></div>

Details:

You're running into a common problem many people run into with React, which is the assumption that setting state is synchronous. It's not. When you call setState, you're requesting that React update the state. The actual state update happens later. This means that immediately after the setState call, the edit element hasn't been created or rendered yet, so the ref points to null.

From the docs:

setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied.


Thank a lot for your answer @rossipedia. I was wondering if I can do it with hooks.

And apparently you can't pass second parameter to useState setter as in setState. But you can use useEffect like this (note second parameter in useEffect):

const [isEditing, setIsEditing] = React.useState(false);
React.useEffect(() => {
    if (isEditing) {
        textInput.current.focus();
    }
}, [isEditing]);

const handleClick = () => setIsEditing(isEditing);

And it worked! ;)

Source: https://www.robinwieruch.de/react-usestate-callback/