LoginSignup
0
0

More than 1 year has passed since last update.

【覚書】React.lazy で import を使わない

Last updated at Posted at 2021-09-19

Dynamic import を何が何でも使いたくなかったので調べた。

こうする

const Hello = React.lazy(() =>
  Promise.resolve({ default: () => <p>Hello!</p> })
);

async/await を使いたいならこう

const Hello = React.lazy(() =>
  (async () => {
    return { default: () => <p>Hello!</p> };
  })()
);

API からデータを持ってくるときはこう

const Response = React.lazy(() =>
  (async () => {
    const res = await (await fetch(API_URL)).json();
    return { default: () => <pre>{JSON.stringify(res, null, 2)}</pre> };
  })()
);

面倒くさいので関数化

const laze = (fn) =>
  React.lazy(() =>
    Promise.resolve(fn()).then((module) => Promise.resolve({ default: module }))
  );

const Hello = laze(() => () => <p>Hello!</p>);

const Response = laze(async () => {
  const res = await (await fetch(API_URL)).json();
  return () => <pre>{JSON.stringify(res, null, 2)}</pre>;
});
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