I am trying to render cards based on some condition using switch case, but the components to which I am not subscribed to using the store variable from redux-toolkit is also getting rendered and this switch is causing to unmount and mount the component, whereas when I use jsx instead of switch it's not getting mounted and unmounted again, why? The scenario is that when I change the value of an object in store this happens, while using switch the whole components unmounts and mounts again.
const cardValue = useSelector(state => state.object.value)
// Using switch statement
function SwitchComponent({ condition }) {
switch (cardValue) {
case 'A':
return <ComponentA />;
case 'B':
return <ComponentB />;
default:
return null;
}
}
return (
<>{SwitchComponent()}</>
)
// Using JSX directly
return (
<>
{cardValue === 'A' ? <ComponentA/> : <ComponentB>}
</>
)
Rendering a component via a ternary or switch statement does not have any effect on how React will render them and whether they get unmounted or not in between renders. It seems your issue comes from both statements having different behavior;
This is basically if "A", render
ComponentAand in all other cases, renderComponentB.But your switch statement does something different;
If "A" render
ComponentAand if "B", renderComponentB, and in all other cases render null. Based on this, I am concluding yourcardValueis not just "A" or "B", but can be another value as well, or possibly temporarily while switching from "A" to "B". To make both statements equal, you could use this for your switch statement: