Reconciliation
React holds the old state as virtual DOM.
When it rerenders it creates a new instance as virtual DOM.
Then it compares
const [isCompany, setIsCompany] = useState(false);
return (
<>
<Checkbox />
{isCompany ? (
<>
Company tax id
<input />
</>
) : (
<>
Person tax id
<input />
</>
)}
</>
Enter some text in the input. Toggle the checkbox. The input value doesn't reset. Why?
React thinks it's the same component, the same input.
Before re-render, isCompany false, Jsx > js
After re-render, isCompany true, Jsx > js
{
type: "form",
props: {
children: [
{type: Checkbox, ...},
{ type: "input", ...}
]
}
}
{
type: "form",
props: {
children: [
{type: Checkbox, ...},
{ type: "input", ...}
]
}
}
React thinks input is the same, so it doesn't remount, it keeps the same element, updates props if needed.
If you want the <input /> to be remounted and state reset, provide a key.
Or change conditional rendering
{isCompany ? ( <> Company tax id <input /> </>) : null}
{isCompany ? null : (<> Person tax id <input /> </>)}
This way the children array has 3
children: [
{type: Checkbox, ...},
{ type: "input", ...},
null
]