Maintaining state within a component (NextJS)

Viewed 24

I have a NextJS app with two very different layouts depending on whether it's in landscape or portrait mode.

My parent page is effectively:

<NavWrapper> <MyPage> </NavWrapper>

The NavWrapper component takes care of the portrait v landscape layouts, and passes {children} into two different components. Each of those components provides the layout, and a container, into which the actual page is rendered.

size.isPortrait? 
<NavPortrait children={props.children}/> : 
<NavLandscape children={props.children}/>

No the problem I'm having is this - Inside 'MyPage' I have a showModal=useState(), which I use to show a pop-up modal. This is working fine. But if I rotate the screen with the modal showing, it disappears. And stays disappeared if I rotate back.

I'm assuming that the change in orientation is causing a fresh instance of 'MyPage' which obviously has the showModal state to the default 'false'.

What's the best way to fix this? Should I have a higher level 'Modal' context? Should I somehow memoise 'MyPage'?

1 Answers

You'll likely need to store the state of showModal at a level higher than MyPage. The code sample you posted indicates that you're rendering a brand new component based on the value of size.isPortrait. You should store the important state at a higher level than your conditional component, and then pass it into the component (either through React Context, props, or some other way.)

If your components do not share any kind of state (or if they do not inherit their state from a singular source), they will always store their state independently.

const [showModal, setShouldShowModal] = useState(false);

return (
 size.isPortrait
    ? 
      <NavPortrait children={props.children} showModal={showModal} /> 
    : 
      <NavLandscape children={props.children} showModal={showModal} />
);
Related