#How to separate content from single route for better code organization?

1 messages · Page 1 of 1 (latest)

neon scarab
#

I am creating a blogging website using React router v7 and in my home page router I have to call multiple apis request for different blog content so, how can I have multiple component so that I can have separate my single route files with multiple component for better code organization and also how can I lazy load the component that are required late in the viewport?

For example my home page route contains highlighted blog, latest blogs with 5 items, featured blogs, trending blogs. So, I have used my loader to get all of this different blogs with 4 API request in loader and pass them to the components as :

export async function loader(){
  const highlighted = await apis.get("/highlighted")
  const latest = await apis.get("/blogs/latest")
  const featured = await apis.get("/blogs/featured")
  const trending = await apis.get("blogs/trending")

  return { highlighted, latest, featured, trending }
}

export default function HomePage({ loaderData }: Route.ComponentProps) {
  const { highlighted, latest, featured, trending } = loaderData;
  return (
    <>
      // highlighted section

      // latest section

      // featured section

      // trending section
    </>
  )
}

This is my coding structure for now. Is this the right way to do or there is better solution for this use case. Any suggestion will be appreciated.

feral pike
#

create the components in another folder like app/components

#

then import them using React.lazy

#

you can wrap them in React.Suspense when rendering, but if you don't React will just wait for the code to be ready before rendering them

#

also don't waterfall your API requests

#

instead of

  const highlighted = await apis.get("/highlighted")
  const latest = await apis.get("/blogs/latest")
  const featured = await apis.get("/blogs/featured")
  const trending = await apis.get("blogs/trending")

you can parallelize them

const [highlighted, latest, featured, trending] = await Promise.all([
  apis.get("/highlighted"),
  apis.get("/blogs/latest"),
  apis.get("/blogs/featured"),
  apis.get("blogs/trending")
])