Skip to content

Code-Splitting frontend routes #92

@jameslindfors

Description

@jameslindfors

This task is an optimization that will reduce initial bundle size and speed up load times. To complete this task, the routes in client/src/app.js need to be lazy loaded and suspended with appropriate error boundaries. This can be achieved by wrapping the entire routes tag in suspense and wrapping the suspense in the error boundary.

Why do we need code-splitting?

When a user goes to a page they are served one large file that contains all the javascript for the frontend. In a small application, this does not affect performance that much. However, as our application grows so does the bundle size. To avoid this we can use a technique called code splitting to 'split' the bundle that the user is served only into what they need at that time. React provides two functions that allow you to easily achieve this: React.lazy and React.suspense.

Resources to get started

Lazy Loading

Using the lazy function from React any import can be lazily loaded. Rather than import Home from './home' each route should be imported as const Home = lazy(() => import('./home'). The old import statements need to be removed so they do not conflict with the lazy imports.

Suspense

Once all the imports are lazy loaded you may receive an error that the suspense is unhandled this is where the React Suspense component comes in. Wrap the <Routes> in <Suspense fallback={}> and handle the fallback with a temporary loading component.

Error Boundaries

Use the react-error-boundary package to handle errors within the route. This takes a fallback error component and a way to reset the state. Wrap <Suspense> in the <ErrorBoundary> component to handle errors within any of the routes.

Note: The code-splitting technique is not limited to routes and could be extended to many components within the project.

This is one step in the process of migrating our build tooling from webpack/CRA to rollup/vite. If you'd like to learn more about the migration plan or want to share your ideas, that discussion can be found here #86

Metadata

Metadata

Assignees

Labels

Frontendtask relates to frontendReactRequire to use React jsenhancementimprove a feature for better usagefeature-requestrequest a new featurehacktoberfestHacktoberfest 2022

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions