Streaming is a good feature in Nextjs, it improve my app’s FCP by separate big chunk into small chunks. but i meet a problem when two streaming rendered component need to interact.
example:
// popup component
function Popup({ popupInfo, visible }) {
return <>{visible && <div className="popup-comp">{popupInfo}</div>}</>;
}
// page component
function Page() {
const [pageInfo, setPageinfo] = useState();
const [popupInfo, setPopupInfo] = useState();
const [visible, setVisible] = useState(false);
useEffect(() => {
fetchPageInfo().then(setPageinfo);
}, []);
useEffect(() => {
fetchPopupInfo().then(setPopupInfo);
}, []);
return (
<div className="page">
{pageInfo}
<button onClick={() => setVisible(true)}>open popup</button>
<Popup visible={visible} popupInfo={popupInfo}></Popup>
</div>
);
}
As shown above, the Popup Component is nested in Page Component, when i click the button it will be shown on the screen. besides, the pageInfo and popupInfo is loaded in useEffect, as we all know, this is a inefficient way to load data.
Fortunately, we can use SSR to load data in sever. furthermore, the pageInfo and popupInfo is independent hence i can use streaming to load these two components independently. but what makes me confused is that how to click button to make the popup visible and how to close it ? or this example is not the correct scene of streaming ?
async function SSRPopup({ visible }) {
const popupInfo = await fetchPopupInfo();
return <>{visible && <div className="popup-comp">{popupInfo}</div>}</>;
}
function Page({ pageInfo }) {
const [visible, setVisible] = useState(false);
return (
<div className="page">
{pageInfo}
<button onClick={() => setVisible(true)}>open popup</button>
</div>
);
}
async function SSRPage() {
const pageInfo = await fetchPageInfo();
return <Page pageInfo={pageInfo}></Page>;
}
function Home() {
return (
<>
<Suspense>
<SSRPage></SSRPage>
</Suspense>
<Suspense>
<SSRPopup></SSRPopup>
</Suspense>
</>
);
}