I'm building a React.js application where I need to conditionally render components based on user interactions (like tabs or dynamic forms). The issue is that when a component is unmounted and later remounted, its local state is lost.
function App() {
const [view, setView] = useState('A');
return (
<>
<button onClick={() => setView('A')}>Show A</button>
<button onClick={() => setView('B')}>Show B</button>
{view === 'A' && <ComponentA />}
{view === 'B' && <ComponentB />}
</>
);
}
function ComponentA() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>Count A: {count}</button>;
}