Joe Schmoe
Joe Schmoe

Reputation: 31

React - how to show/hide components so that state persists even when a component isn't rendered

I have a main component which has 3 child components which are conditionally displayed. There are arrow buttons to change which child component is rendered. One of the children has states which need to persist even when the component is no longer the child which is displayed.

The problem is, I don't feel like the state data from this child component should be passed back to the parent as the method to maintain state. In this scenario i want the child's state to only live in the child component. Is there a method i could use to maintain this state? For example, will the state persist if i render each child but use CSS (or some other option) to conditionally hide the non-active child?

Upvotes: 0

Views: 424

Answers (1)

Luis Gurmendez
Luis Gurmendez

Reputation: 664

You can add display: none, and the component will still be mounted and will keep the state. Although this might work I recommend lifting the state up to the parent. It seems like it should live there. Otherwise you can create a context wrapping the 3 children and manage the state there. Then in each child can subscribe to that context, but it seems like an over kill. I recommend lifting the state to the parent

Upvotes: 2

Related Questions