0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

lazy loadingでルーティング

Posted at

lazy loadingとは?

Lazy Loading(遅延読み込み)は、初期ロード時のパフォーマンスを向上させるために使われます。
アプリケーション内のルートやページコンポーネントを必要なときにだけ読み込むことで、初期表示の速度を向上させます。

lazy loading する前のコード

ルートのページコンポーネントとしてHome, About, Contactをimportしています。
ですがこのままだと全てのコードを1つのファイルにまとめるため、
初期ロード時に大きなJSファイルをダウンロードすることとなり、
初期表示が遅くなります。
なので必要な時だけ各ページコンポーネントがimportされるようにしたいです。

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import NavBar from "./components/NavBar";
// 下記三つがlazy loadの対象
import Home from "./components/Home";
import About from "./components/About";
import Contact from "./components/Contact";

function App() {
  return (
    <div className="p-8">
      <Router>
        <NavBar />
        <Routes>
          <Route path="/" element={<Home />}></Route>
          <Route path="/about" element={<About />}></Route>
          <Route path="/contact" element={<Contact />}></Route>
        </Routes>
      </Router>
    </div>
  );
}

export default App;

lazy loading した後のコード

各ページコンポーネントはlazy loadingにしましたので、
Suspenseでロード中のfallbackを設定しました。

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import NavBar from "./components/NavBar";
import { lazy, Suspense } from "react";

// lazy loading の設定
const Home = lazy(() => import("./components/Home"));
const About = lazy(() => import("./components/About"));
const Contact = lazy(() => import("./components/Contact"));

function App() {
  return (
    <div className="p-8">
      {/* Suspenseで囲む */}
      <Suspense fallback={<p>Loading...</p>}>
        <Router>
          <NavBar />
          <Routes>
            <Route path="/" element={<Home />}></Route>
            <Route path="/about" element={<About />}></Route>
            <Route path="/contact" element={<Contact />}></Route>
          </Routes>
        </Router>
      </Suspense>
    </div>
  );
}

export default App;

まとめ

  • Routingなど、ユーザーのアクションによって表示が切り替わるものは、逆を返すと表示しなくていいものもあるので、lazy loadingでimportしましょう
  • lazy loadingを設定するとユーザーのアクションにより読み込む必要性が出てくるので、Suspenseで囲って、fallbackコンテンツを用意しましょう
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?