日本語

React input loses focus after each keystroke: fixing nested components

​​React​ESLint,Forms,TypeScript,useState

In a React form, an input can lose focus after you type one character, so you cannot type the second character. This happens when the input's component is defined inside the parent component. Move the input's component to the top level of the file and pass the value and change function as props to fix it.

This pattern appears when you want to use the parent's state in a search or contact form and make the input a component inside the parent. I tested in a test environment. I compared the version with the component defined inside the parent against the fixed version, and checked what happened when I typed "neko" on the keyboard.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, react / react-dom 19.3.1, and TypeScript 6.0.3. I type-checked the .tsx files with tsc, bundled them for development with esbuild, and typed into them in Chromium 153 driven by Playwright 1.63.0. I did not use StrictMode, so that remount records would not mix into the results. I did not test under Vite or Next.js, in browsers other than Chromium, or in builds with the React Compiler enabled.

An input defined inside the parent stops after the first character

In the NestedForm below, the name is held in state, and the input that uses that state is a component called NameField. NameField is defined inside the NestedForm function. The useEffect is test code that records mounting and unmounting. In the code in this article, the import lines are omitted.

tsx
export function NestedForm() {
  const [name, setName] = useState('');

  function NameField() {
    useEffect(() => {
      log('マウント(NameField)');
      return () => log('アンマウント(NameField)');
    }, []);
    return <input value={name} onChange={(e) => setName(e.target.value)} />;
  }

  return (
    <div>
      <NameField />
      <p>入力した名前:{name}</p>
    </div>
  );
}

I clicked the input and typed "n", "e", "k", and "o" one at a time on the keyboard. The "focus" in each line is the element that had focus at that moment. "Same input element as before" was checked by writing a marker attribute onto the input element before typing, then checking whether that marker was still there.

text
--- NestedForm ---
  [マウント(NameField)]
  > 入力欄をクリックして、キーボードで "neko" と打つ(1文字ずつ)
  [アンマウント(NameField)]
  [マウント(NameField)]
  「n」のあと: 入力欄="n" / 入力した名前:n / フォーカス=body / 最初と同じ input 要素か=false
  「e」のあと: 入力欄="n" / 入力した名前:n / フォーカス=body / 最初と同じ input 要素か=false
  「k」のあと: 入力欄="n" / 入力した名前:n / フォーカス=body / 最初と同じ input 要素か=false
  「o」のあと: 入力欄="n" / 入力した名前:n / フォーカス=body / 最初と同じ input 要素か=false

The first character, "n", was entered, but focus then moved to body, and the remaining three characters went nowhere. The input element had also changed to a different element from the one I first clicked.

When I clicked the input again before each character, all four characters were entered. However, each keystroke logged an unmount and a mount, and focus returned to body every time. The following output shows only the first two characters.

text
  「n」のあと: 入力欄="n" / フォーカス=body
  [アンマウント(NameField)]
  [マウント(NameField)]
  「e」のあと: 入力欄="ne" / フォーカス=body

The following GIF shows the input with NameField defined inside the parent at the top, and the input with NameField moved outside at the bottom. The fix is explained in a later section. Each input received "neko" typed on the keyboard.

Two inputs, top and bottom, with neko typed into each in turn. In the top input, which is defined inside the parent, focus is lost after n is typed and the input stays at n. In the bottom input, which is moved outside, focus stays and neko is entered in full.
Typing one character at a time on the keyboard into the input defined inside the parent (top) and the input moved outside (bottom)

It is recreated as a different component on every render

Each time you type a character, setName is called, and NestedForm renders again. At that point, function NameField() { … } runs again, so a new function is created that differs from the previous one.

React decides whether something rendered at the same position is the same kind of component by comparing the component function itself. If the function is different, React treats it as a different kind of component. It unmounts the previous NameField and mounts the new one. The official documentation section on state being reset when the component type changes at the same position uses this pattern as an example. It recommends declaring component functions at the top level, not nesting them.

When a component unmounts, its DOM elements are removed along with its state (ESLint static-components rule documentation). The focused input element disappeared from the page. The newly created input does not have focus, so the characters typed afterward went nowhere. This is why, in the test, focus moved to body, and the input was replaced by one without the marker.

Move it outside and pass the value and change function as props

Move NameField to the top level of the file. The parent's state cannot be read directly from there, so the component receives the value, and a function to call on change, as props.

tsx
type NameFieldProps = {
  value: string;
  onChange: (e: ChangeEvent<HTMLInputElement>) => void;
};

function NameField({ value, onChange }: NameFieldProps) {
  // (useEffect that records mounting is omitted)
  return <input value={value} onChange={onChange} />;
}

export function TopLevelForm() {
  const [name, setName] = useState('');
  return (
    <div>
      <NameField value={name} onChange={(e) => setName(e.target.value)} />
      <p>入力した名前:{name}</p>
    </div>
  );
}
text
--- TopLevelForm ---
  [マウント(NameField)]
  > 入力欄をクリックして、キーボードで "neko" と打つ(1文字ずつ)
  「n」のあと: 入力欄="n" / 入力した名前:n / フォーカス=input / 最初と同じ input 要素か=true
  「e」のあと: 入力欄="ne" / 入力した名前:ne / フォーカス=input / 最初と同じ input 要素か=true
  「k」のあと: 入力欄="nek" / 入力した名前:nek / フォーカス=input / 最初と同じ input 要素か=true
  「o」のあと: 入力欄="neko" / 入力した名前:neko / フォーカス=input / 最初と同じ input 要素か=true

The component mounted only once, and all four characters were entered. NameField is the same function, defined once, so it stays the same kind of component even when TopLevelForm renders again. The input element is not recreated. The same element receives a new value.

Point

When you want to use the parent's state inside a component, don't define the component inside the parent. Pass the state in as props. The official documentation also explains that the urge to define a component inside another one is a sign that it should receive props instead (note on using parent state in the static-components documentation).

For a small part, putting the JSX in a variable is enough

If the input is used in only one place, you can fix the problem without making it a component by putting its JSX in a variable.

tsx
export function JsxVariableForm() {
  const [name, setName] = useState('');
  const nameField = <input value={name} onChange={(e) => setName(e.target.value)} />;
  return (
    <div>
      {nameField}
      <p>入力した名前:{name}</p>
    </div>
  );
}
text
--- JsxVariableForm ---
  > 入力欄をクリックして、キーボードで "neko" と打つ(1文字ずつ)
  「n」のあと: 入力欄="n" / 入力した名前:n / フォーカス=input / 最初と同じ input 要素か=true
  「e」のあと: 入力欄="ne" / 入力した名前:ne / フォーカス=input / 最初と同じ input 要素か=true
  「k」のあと: 入力欄="nek" / 入力した名前:nek / フォーカス=input / 最初と同じ input 要素か=true
  「o」のあと: 入力欄="neko" / 入力した名前:neko / フォーカス=input / 最初と同じ input 要素か=true

nameField is not a function. It is the JSX for an <input> that is created on each render. From React's point of view, an input element is always at the same position, so the element is not recreated.

Wrapping it in useCallback does not fix it

If the cause is that the function changes every time, you might think that wrapping it in useCallback to reuse the same function would fix it. The input reads name, so name goes into the dependency array.

tsx
export function UseCallbackForm() {
  const [name, setName] = useState('');

  const NameField = useCallback(() => {
    return <input value={name} onChange={(e) => setName(e.target.value)} />;
  }, [name]);

  return (
    <div>
      <NameField />
      <p>入力した名前:{name}</p>
    </div>
  );
}
text
--- UseCallbackForm ---
  > 入力欄をクリックして、キーボードで "neko" と打つ(1文字ずつ)
  「n」のあと: 入力欄="n" / 入力した名前:n / フォーカス=body / 最初と同じ input 要素か=false
  「e」のあと: 入力欄="n" / 入力した名前:n / フォーカス=body / 最初と同じ input 要素か=false
  「k」のあと: 入力欄="n" / 入力した名前:n / フォーカス=body / 最初と同じ input 要素か=false
  「o」のあと: 入力欄="n" / 入力した名前:n / フォーカス=body / 最初と同じ input 要素か=false

The result was the same as defining the component inside the parent. As described in the useCallback reference, when a dependency value changes from the previous render, useCallback returns the new function passed in that render. Typing one character changes name, so NameField again becomes a different kind of component.

Finding it with ESLint's static-components rule

eslint-plugin-react-hooks has a static-components rule that catches components created inside components, and it is included in the recommended config. In the test, I used version 7.1.1 and checked .tsx files with the following config.

js
import tseslint from 'typescript-eslint';
import reactHooks from 'eslint-plugin-react-hooks';

export default [
  { files: ['src/**/*.tsx'], languageOptions: { parser: tseslint.parser } },
  reactHooks.configs.flat.recommended,
];

When I put the four patterns from this article into one file and ran the check, two places were reported as errors: NestedForm, which defines the component inside the parent, and UseCallbackForm, which wraps it in useCallback. The version with the component moved outside and the version with JSX in a variable had no errors. In the output below, I replaced the working directory path with /path/to/app and omitted part of the extracted code.

text
/path/to/app/src/cases.tsx
  19:8  error  Error: Cannot create components during render

Components created during render will reset their state each time they are created. Declare components outside of render.
(中略)
  71:8  error  Error: Cannot create components during render
(中略)
✖ 2 problems (2 errors, 0 warnings)

The message means: "Components cannot be created during render. Components created during render reset their state each time they are created, so declare them outside of render." A focus-loss bug is hard to notice without actually using the form, so turning this rule on catches it when you write the code.

​Posted by 86