Technologies:
Tolerim
a month ago
Reworded sentence: What are the effects of placing a component within a parent component?
import { useState } from 'react';
const Form = () => {
const [values, setValues] = useState(['', '']);
const onChange = (value, index) => {
const newValues = [...values];
newValues[index] = value;
setValues(newValues);
};
const Input = (props) => {
return <input type='text' {...props} />;
};
return (
<>
{values.map((value, index) => (
<Input
key={index}
value={value}
onChange={(e) => onChange(e.target.value, index)}
/>
))}
<button onClick={() => setValues([...values, ''])}>Add</button>
</>
);
};
Answers(2)
Vogi
a month ago
Verified Answer
Thank you for sharing your experience. When a parent component re-renders, React will also re-render all of its child components. In this case, the child component is re-rendered when the parent component is re-rendered because it is defined inside the parent component. This can cause performance issues if the child component is complex and has a lot of logic. Defining the child component outside of the parent component can help avoid these issues. I hope this helps! Let me know if you have any other questions.
Tolerim
a month ago
When the parent component re-renders, the child functional component does get re-rendered as well, unless you take steps to prevent it. "Re-declared" in this context means that the child component is re-created (instantiated) with each render of the parent component. In the code example given, the Input component is defined inside the Form component, so it gets re-created with each re-render of the Form component, causing the input focus to be lost. To fix this, you can either pass the component itself () instead of re-declaring it with each render, or define the child component outside of the parent component, effectively "hoisting" it up.