Use Preact in Next.js 13
November 27, 2022
4 min read
Next.js uses React by default. In this blogpost, I want to replace React with Preact and compare the build differences.
Why Replace React
There are a few reasons why you would do this and there are some other posts that explain it very well.
The key distinction is that Preact lacks several of the experimental features included in React, like Suspense and Concurrent Mode. You have a strong argument for replacing React with Preact if you don't use any of these of the more sophisticated features of React.
I'll summarize some of the reasons you should replace React with Preact.
- Preact provides the thinnest possible Virtual DOM abstraction on top of the DOM.
- Preact has a small size!
- Preact is fast, and not just because of its size.
- Preact is highly compatible with React API and supports the same ECMA Script
- Preact has a package named preact/compat to let developers use React libraries with Preact.
Learn more about the differences of Preact from React here
Let's start by creating a new Next.js app.
Next, we need to install Preact in app.
app Directory in Next.js 13
Next.js 13 introduces layouts with the
app directory. To use the
app directory, add the following to your
In the main directory, create an
app directory and a
hello directory in the
app directory. Add a
page.tsx in the
app directory should look like this
layout.tsxwill be generated when you start your server in dev environment.
Add the following to your
Replace the contents of
pages/index.tsx with a simple page component.
Run your app with
pnpm dev and inspect http://localhost:3000/ and http://localhost:3000/hello to confirm everything is working.
Once everything is working, we need to swap React with Preact in our Next.js app.
We need to tell Next.js that we'd like to swap out React for Preact by using Webpack's aliasing feature only in client production build. The
dev server will run with React.
Let's update our
next.config.js with the following
Once you build your Next.js application with
next build, you should see a decrease in bundle size. Compare the build results for our demo application.
The Preact Team provides a plugin for use with Next.js. It works in both
Install the plugin
Use the plugin your
next.config.js like this
If you are not using any experimental React features in your Next.js app, I would recommend replacing React with Preact to reduce your bundle size by a considerable chunk.
Checkout Repo on Github