I have 2 react components X and Y. X holds state which is calculated through different types of logic and through user input. Users can click on a button in X which will unmount X and render Y. Now there also exists a button on Y which when clicked unmounts Y and renders X again, however X no longer has its state because it was lost when the component was unmounted when we first rendered Y. How can I ensure that X "holds" onto its state even when it gets unmounted?
I've tried passing X's state as a prop to Y, but I'm not sure if I can pass this prop on Y back to X when Y unmounts?
CodePudding user response:
For all the state that needs to be accessed through both X and Y, initialize it in a parent component of both X and Y, then pass the state and its setters down to both. For example:
const App = () => {
const [showY, setShowY] = useState(false);
const [persistentXState, setPersistentXState] = useState('');
return showY
? <Y {...{ setShowY }} />
: <X {...{ setShowY, persistentXState, setPersistentXState }} />;
};
This way, X can use its persistentXState prop and call setPersistentXState, and it'll persist even after setShowY
gets called to unmount X and show Y again.
CodePudding user response:
Yes, this is a classic case of lifting state up. You absolutely can pass state up from Y using callbacks and setting it in the state of the parent. Then pass it to Y again.
There is another trick, but it keeps both in memory so might not be the best: you can display: none
using CSS instead of unmounting, which means its there but the user just cant see it.