API 파이프라이닝
위와 같이 엔트리 파일에서 리액트 앱 초기화와 API 요청을 동시에 수행해 초기 렌더링까지 걸리는 시간을 단축할 수 있어요. Stackflow Future API를 활용하면 API 파이프라이닝을 깔끔한 방법으로 구현할 수 있어요.
entry.ts
import { makeTemplate } from "@stackflow/plugin-history-sync";
import { config } from "./stackflow/stackflow.config";
async function main() {
let initialLoaderData: unknown | null = null;
for (const activity of config.activities) {
const t = makeTemplate({ path: activity.route });
const match = t.parse(location.pathname + location.search);
if (!match) {
continue;
}
// 1. API 데이터를 요청해요 (await하지 않아요)
initialLoaderData = activity.loader({ params: match as any });
break;
}
// 2. 동시에 리액트 앱을 다운로드 받아요.
const { renderApp } = await import("./renderApp");
// 3. 둘을 결합해요.
renderApp({ initialLoaderData });
}
main();
Stack에 initialLoaderData를 전달하면 첫번째 loader를 실행시키는 대신 받은 loaderData로 결과를 덮어써요.
renderApp.ts
export function renderApp({ initialLoaderData }: { initialLoaderData: unknown }) {
const root = ReactDOM.createRoot(document.getElementById("root")!);
root.render(
// 에러와 로딩 처리는 React에서 가능해요
<ErrorBoundary>
<Suspense>
<Stack initialLoaderData={initialLoaderData} />,
</Suspense>
</ErrorBoundary>
);
}