While developing, I extracted part of the content from the parent component into a child component, which is naturally more complex than the code in the example. When I try to enter text in the input box, it loses focus after each input. So I have written similar code to illustrate the issue. Could you please help me resolve this?
import { useState } from 'react';
function App () {
const [text, setText] = useState('');
const handleChange = (event) => {
setText(event.target.value);
};
const Input = () => (<input value={text} onChange={handleChange} />)
return (
<div className="App">
<Input />
</div>
);
}
export default App;
3
Answers
Such a new way to write I’ve never thought of it before.
It’s definitely because rerendered, but how it worked maybe need to read react source code.
Maybe you could try the following code?
What you did is a declaration of a component within a component:
Jack Herrington talks about it in his video "3 React Mistakes, 1 App Killer"
More in depth explanation: the reason is the mechanism of reconciliation. React compares current shape of Virtual DOM to previous shape. Among other things, the identity of each element is compared, i. e. the reference to the function which creates the element. You create a new reference to
Input
on each render ofApp
and this is whyInput
is dismounted and remounted on eachtext
change. I don’t understand why you did that, just do this:Move the creation of your
Input
component outside of the App component (or into a separate file andimport
it), and pass down the relevant props. Currently the component is being recreated on each new render when the state changes.