Future API
API 파이프라이닝

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: any | null = null;
 
  for (const activity of config.activities) {
    const t = makeTemplate({ path: activity.path });
    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();
/**
 * renderApp.tsx
 */
export function renderApp({ initialLoaderData }: { initialLoaderData: any }) {
  const root = ReactDOM.createRoot(document.getElementById("root")!);
 
  root.render(
    // 에러와 로딩 처리는 React에서 가능합니다
    <ErrorBoundary>
      <Suspense>
        {/**
          * Stack에 initialLoaderData를 넘겨주면
          * 첫번째 loader를 실행시키는 대신 받은 loaderData로 결과를 덮어씁니다
          */}
        <Stack initialLoaderData={initialLoaderData} />,
      </Suspense>
    </ErrorBoundary>
  );
}