September 01, 2022 âą 5691 Views âą 17 min read
Tetiana Stoyko
CTO & Co-Founder
Clearly, before explaining how to convert React to Next.js it is worth explaining the reason and advantages of such a process. Therefore, let's briefly discuss both software and its pros and cons.
Actually, we have already spoken about ReactJS, the reasons why you should and shouldn't use React for your project, and compared it with other alternatives. Therefore, if you are looking for a more detailed explanation, you are welcome to read the previous article.
So as not to repeat ourselves and to avoid unnecessary text injections, let's just briefly sum up the previously mentioned article.
React is an open-source front-end library, based on JavaScript. It is used to develop user interfaces and thanks to some specifics is capable of supporting multiple media components or other visual content.
Among the advantages of using React, we can highlight:Â
However, it is obvious, that there are lots of disadvantages too. Clearly, if everything was so great, there would be no need to migrate from this software. So what is wrong with React apps? It is possible to underline several major drawbacks of this library:
Next.js is an open-source framework, based on React. It is even possible to say, that it is a deep modification of React library.
For instance, in addition to common React functions, Next supports server-side rendering, which helps to increase the performance and improves the user experience. Furthermore, Next has improved SEO efficiency. As a result, Next.js provides the same functions as React but also covers its shortcomings.
Frankly speaking, Next.js is a much better choice for a number of reasons. In addition to its SEO-friendly status and improved server-side rendering, as well as React features, it has great potential due to the fact it is a relatively new framework, that keeps growing.
If all the foregoing haven't convinced you, let's briefly list Next.js features:
Among the drawbacks of Next.js we can name:
Eventually, it is time to talk about the practical side of migration. We decided not to explain each of the steps in detail, but rather to create step-by-step instructions with source code and brief explanations. So what does the migration from React to Next.js looks like on the code level?
First of all, let's make changes to the dependencies and scripts in the package.json. Before starting an actual coding we need to remove âreact-scriptsâ and âreact-router-domâ. Then, we have to install "next". After these actions, we can start changing the scripts.
For instance, we need "next dev" to start the developer server on "localhost:3000", "next build" for creating a production build, and "next start" for running this build:
{
"name": "migration-to-next-from-react",
"version": "0.1.0",
"private": true,
"dependencies": {
 "next": "^12.2.0",
 "react": "^18.2.0",
 "react-dom": "^18.2.0"
},
"scripts": {
 "dev": "next dev",
 "start": "next start",
 "build": "next build"
},
}
After the dependencies were changed and new scripts are created, we can transfer our assets such as videos, photos, and any other static assets to the "public" directory. The reason is simple - React uses the "public" folder to keep static assets and entry HTML files. In Next.js we use this folder just for assets:
To perform the foregoing action, we need to migrate all contests of <head> from index.html to _document.js. Replace <head> and <html> tags with custom components from the Next.js library. Add <Main /> and <NextScript /> into <body>. Any external scripts, that we used into <head> we also need to add in _document.js:
import Document, { Html, Head, Main, NextScript } from "next/document";
class MyDocument extends Document {
render() {
 return (
  <Html>
   <Head>
    <meta charset="utf-8" />
    <link rel="icon" href="./favicon.png" />
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin />
    <title>Easy migration to next!</title>
   </Head>
   <body>
    <Main />
    <NextScript />
   </body>
  </Html>
 );
}
}
export default MyDocument;
Then, we need to create the _app.js entry point. Here you can migrate all shared layouts. Itâs worth stopping hydration on the server-side because our app might use some browser API, such as âwindowâ, that does not exist on the server. So, we can create the custom wrapper <StopHydrationWrapper> or something like that:
const StopHydrationWrapper = ({ children }) => {
return <div>{typeof window === "undefined" ? null : children}</div>;
};
const MyApp = ({ Component, pageProps }) => {
return (
 <StopHydrationWrapper>
  <Component {...pageProps} />
 </StopHydrationWrapper>
);
};
export default MyApp;
Important things to know:
_document.js and _app.js must be in the âpagesâ directory ( ./pages/_app.js ).
The ânextâ folder is a folder that contains our static build. So, we must add â.nextâ to â.gitignoreâ.
Next.js has a filesystem-based router based on the concept of pages. Once the file is added to the âpagesâ directory, it is automatically available as a route. Usually, in React apps we use the âreact-router-dom" library for routing. So, we must convert our React router system to the build-in Next.js router:
<Switch>
     <Route path="/users" render={() => <Users />} />
     <Route path="/posts/:userId?" render={() => <Posts />} />
     <Route
      path="/post/:postId?"
      render={() => <PostDetails />}
     />
</Switch>
And this is converted Next.js routing:Â
For SEO we must add âtitleâ and âmetaâ tags to the <Head> component on all our pages. This is how it can look:
<>
    <Head>
     <title>{seoTitle}</title>
     <meta property="og:type" content="article" />
     <meta name="description" content={seoDescription} />
     <meta name="keywords" content={seoKeywords} />
    </Head>
    <Users />
</>
Usually, the React.js app fetches data for components in the âuseEffectâ hook. But if we do fetching in this way, we will make requests on the client-side. For server-side data fetching in Next.js, we will use the âgetStaticPropsâ and âgetServerSidePropsâ functions. When they are executed is the primary distinction between âgetServerSidePropsâ and âgetStaticPropsâ. Every time a user makes a new request to the page, âgetServerSidePropsâ is executed. And âgetStaticPropsâ runs when static pages are built.Â
const User = ({ user }) => {
return (
 <div>
  <img src={user.avatar} alt={user.name} />
  <div>
   <span>{user.name}</span>
   <span>{user.email}</span>
  </div>
 </div>
);
};
export async function getServerSideProps(context) {
const { id } = context.query;
const user = await getUser(id);
return {
 props: {
  user,
 },
};
}
export default User;
const Posts = ({ posts }) => {
return (
 <div>
  {posts.map((post) => (
   <Post key={post.id} post={post} />
  ))}
 </div>
);
};
export async function getStaticProps() {
const posts = await getPosts();
return {
 props: {
  posts,
 },
};
}
As a result, if you have done all the previous steps correctly - Congratulation, you have successfully migrated from React to Next.js as well as set up some of the basic features for your app. Clearly, if there are any additional functions or features you want to implement, you can do it as well.
We hope that this brief explanation and tutorial will help you to better understand all the possible advantages of converting React to Next.js and can become a basic setup for the future transformation of your project.
Clearly, each software has its own pros and cons, however, we highly encourage you to perform such migration as soon as possible. The reasons are simple: Next.js allows you to use most React functions and provides more additional features and instruments.
It would be fair to assume, that Next.js is a deep modification of React, that helps to develop full-fledged standalone applications without using additional software. Moreover, the migration process itself is very simple and won't take much time. Also, such simplicity enables the possibility to develop apps, based on React and afterward transfer them to Next if needed. If you wonder what apps can be developed with React, or what functionality is possible - you can examine some of our cases.
Share this post
Tags
Love it!
Valuable
Exciting
Unsatisfied
YOU MAY ALSO LIKE
Letâs talk!
This site uses cookies to improve your user experience.Read our Privacy Policy
Accept