Material UI portal component vanishes after page refresh in next.js

I use Next.js and Material UI. I need to render an element in another place, because of the Swiper library that I use.

For this purpose, I’m using Material UI’s <Portal> component and here’s my code:

import { useRef } from 'react'
import Portal from '@mui/material/Portal';

//more code here

const container = useRef(null);

//more code here

<div ref={container}></div>

//more code here

<Swiper
    spaceBetween={20}
    slidesPerView={1}
>
    <Portal container={container.current}>
        <SwiperButton></SwiperButton>
    </Portal>
    {
        ads.map(ad => <SwiperSlide key={ad.imageUrl}>
            <div>{ad.title}</div>
        </SwiperSlide>
        )}
</Swiper>

This code works just fine for the first load of my web page. But as soon as I refresh the web page, it vanishes and disappears completely and there is no error whatsoever in the console.

And no matter what I do, it won’t come back. Ctrl+F5 does not work and stopping and destroying and recreating my container does not work.

The only way to make it work is to comment that part of code, load the page and uncomment it again.

Why is it so, and how can I fix this problem?