DEV Community

Cover image for 7 ways to generate a react project
Vishal Sharma
Vishal Sharma

Posted on • Originally published at codeentity.tech on

7 ways to generate a react project

Creating a new React application is not a simple task.

Creating a new React application requires careful consideration of various factors that will impact its scalability, collaboration and compatibility with your current and future tools and needs. These decisions include the type of app you are building (e.g. Complex web app, static landing site , content heavy blog site or an seo targeted e-commerce app), the level of server engagement, the number of developers working on the app, the reuse of components from other applications, and the build and deployment process. These decisions should be made with your end goal in mind and will require a significant amount of effort to ensure the success of the app.

So let’s start with what’s React?

React is a JavaScript library for building user interfaces. It was developed by Facebook and is widely used for building web and mobile applications. React allows developers to create reusable components that can be easily managed and composed to build complex user interfaces. React uses a virtual DOM (Document Object Model) to optimize the rendering of components and improve the performance of the application.

In this article

This article presents a collection of the methods, frameworks and tools for creating React applications. These options range from optimizing for quick setup for small websites (or just to test react) to catering to global scale, and some even do both. I hope that this article will assist you in constructing a React application that satisfies your needs, reduces errors and time wasted in the process.

1. Nothing but React

You can include the React bundle from a CDN directly in your HTML file to quickly get a taste of how React works and what it can do. However, this method is not recommended for creating production applications.

To use React from a CDN (Content Delivery Network) in an HTML file, you can include the React and ReactDOM libraries by adding script tags to the head of your HTML file.

Here is an example of how to include React and ReactDOM from a CDN in an HTML file:

<!DOCTYPE html>
<html>
  <head>
    <script src="https://unpkg.com/react@18.2.0/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@18.2.0/umd/react-dom.development.js"></script>
  </head>
  <body>
    <!-- your HTML content goes here -->
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Note that the exact URL of the React library may vary depending on the version of React that you want to use. You can find the latest version of React and ReactDOM at the following URLs:

Once you have included the React and ReactDOM libraries in your HTML file, you can use React to create and render components in your application.

For example, you can create a simple React component using the React.createElement function and render it to the page using theReactDOM.render function:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>React CDN</title>
  </head>
  <body>
    <div id="root"></div>
    <script src="https://unpkg.com/react@18.2.0/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@18.2.0/umd/react-dom.development.js"></script>
    <script>
      ReactDOM.createRoot(document.getElementById("root")).render(
        React.createElement("h1", null, "Hello world!")
      )
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

This will render an h1 element with the text Hello world!.

Using this way use can not use .jsx syntax because we don’t have babel parser in place to parse and covert the syntax to plain JS.

2. From Scratch (Without any tooling)

React and React DOM are JavaScript libraries that are typically installed via the npm package manager. These libraries provide the building blocks for creating web applications using the React framework.

Once React and React DOM are installed, it is common to also set up a build tool such as webpack and a transpiler such as Babel in order to bundle and transpile the code for the application. This process involves creating configuration files that specify how webpack and Babel should be used to build the application.

Overall, the process of setting up a React application involves installing the necessary npm packages and configuring webpack and Babel to properly build and transpile the code. This allows developers to manage all of the build-related configuration in a centralized location, making it easier to maintain and update the application as it grows.

I have written a detailed blog explaining this method. Read it here

3. Next.js

Next.js is a popular framework for building server-rendered React applications. It provides a simple and efficient way to create React projects with automatic code splitting, server-side rendering, and optimized performance.

To generate a new React project using Next.js, you can follow these steps:

  1. Install the create-next-app command-line tool by running npm install -g create-next-app. This will allow you to easily create a new Next.js project.

  2. Create a new Next.js project by running the create-next-app command and specifying a name for your project:

create-next-app my-project or use npx create-next-app my-project which don’t require you to install create-next-app package locally.

This will create a new directory with the specified name and generate the basic file structure and configuration for a Next.js project.

  1. Navigate to the new project directory and install the dependencies by running npm install.

  2. Run the development server by running npm run dev. This will start the development server and open a new browser window with your Next.js app.

  3. Modify the pages/index.js file to modify the homepage and add content to your app.

  4. Next.js uses the pages directory to define the routes of your app. Each JavaScript file in the pages directory corresponds to a route, and the components exported from those files are rendered when the corresponding route is accessed.

For example, the pages/index.js file defines the root route of the app, and the components exported from this file are rendered when the root route is accessed.

  1. To create a new route create a new js file in pages directory and default export the react component. Next will create a route for you with name of the js file.

For example, create pages/newPage.js file and next will create /newPage route.

  1. Next by default will server side render each page and will return static html along will react bundle to browser.
  2. You can also create dynamic routes in pages directory. Dynamic routes are routes that have a variable component, such as /posts/:id or /users/:username. These routes allow you to render different content for each value of the variable component. For example To create a dynamic route for /posts/:id create a folder with name posts in pages directory and inside this folder create file [id].js. Along with this you can create an index.js which will render on /posts route.

Along with a react component you can also use lifecycle methods of next.js.

In a Next.js page getServerSideProps, getInitialProps, getStaticPaths, and getStaticProps are functions that can be used to fetch data or perform other tasks before a page is rendered. These functions are called “lifecycle methods” because they are executed at different stages of the page rendering process.

Here is a brief overview of these lifecycle methods:

  • getServerSideProps is a function that is executed on the server side before the page is rendered. It allows you to fetch data or perform other tasks that require server-side rendering, such as server-side rendering with authenticated content or server-side rendering with a database. The results of getServerSideProps are passed to the page as props.
  • getInitialProps is a legacy function that was used in Next.js versions prior to 9.3. It is similar to getServerSideProps but is executed on the server side as well as the client side. If you are using a version of Next.js prior to 9.3, you can use getInitialProps to fetch data or perform other tasks before the page is rendered.
  • getStaticProps is a function that is executed at build time to generate static pages. It allows you to fetch data or perform other tasks that do not require server-side rendering, such as generating static pages with data from an API or a file system. The results of getStaticProps are passed to the page as props and are available at runtime.
  • getStaticPaths is a function that is used in conjunction with getStaticProps to generate static pages for dynamic routes.To generate static pages for dynamic routes, you need to specify the values of the variable component that you want to pre-render. You can do this by implementing the getStaticPaths function in your page file.

In general, you should use getServerSideProps when you need to perform server-side rendering, such as with authenticated content or a database. You should use getStaticProps when you need to generate static pages, such as with data from an API or a file system, getStaticPaths to create and return list of dynamic paths on build time . You should avoid using getInitialProps if you are using a version of Next.js newer than 9.3.

By using these lifecycle methods, you can control the data and behavior of your pages in a Next.js application and optimize the rendering process for different scenarios.

Here is an example of a page file with all lifecycle methods

// pages/posts/[id].js
import React from "react"
// Server Side fetch
import fetch from "node-fetch"

const Posts = () => {
  return (
    <div>
      <h1>Hello, world!</h1>
      <p>Welcome to my Next.js application.</p>
    </div>
  )
}

// This gets called on every request
export async function getServerSideProps() {
  // Fetch data from external API
  const res = await fetch(`https://.../data`)
  const data = await res.json()

  // Pass data to the page via props
  return { props: { data } }
}

// This function gets called at build time
export async function getStaticPaths() {
  // Call an external API endpoint to get posts
  const res = await fetch("https://.../posts")
  const posts = await res.json()

  // Get the paths we want to pre-render based on posts
  const paths = posts.map(post => `/posts/${post.id}`)

  // We'll pre-render only these paths at build time.
  // { fallback: false } means other routes should return 404.
  return { paths, fallback: false }
}

// This also gets called at build time
export async function getStaticProps({ params }) {
  // params contains the post `id`.
  // If the route is like /posts/1, then params.id is 1
  const res = await fetch(`https://.../posts/${params.id}`)
  const post = await res.json()

  // Pass post data to the page via props
  return { props: { post } }
}

export default Posts
Enter fullscreen mode Exit fullscreen mode
  1. Finally Next also provides a way to create api routes. Create api folder inside pages and inside this create apiRoute.js. Here you can default export a function to handle api calls to /api/apiRoute.js. Inside the function we can use switch case statement to handle api methods like GET, POST.
export default function handler(req, res) {
  const { method, body } = req

  switch (method) {
    case "POST": {
      res.status(200).json({ name: "John Doe", method })
    }
    case "GET": {
      res.status(200).json({ name: "John Doe", method })
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. To build your Next.js app for production, run the npm run build command and then the npm run start command to start the production server.

Overall next.js is a good to go if your application involves lots of dynamic rendering and routing but you also want to use server side rendering to improve page performance and seo.

4. Gatsby

Gatsby.js is a static site generator for React that allows you to build fast and modern websites. It comes GraphQL out of the box to access data. GraphQL allows you to declaratively express your data needs. This is done with queries, queries are the representation of the data you need.

GraphQL is certainly not required, but the benefits of adopting GraphQL are significant. GraphQL will simplify the process of building and optimizing your pages, so it’s considered a best practice for structuring and writing Gatsby applications.

One of the key benefits of Gatsby.js is it let’s you create multiple pages using a single template on build time. In gatsby-node.js, you can use the GraphQL query to generate pages.

exports.createPages = async ({ graphql, actions, reporter }) => {
  const { createPage } = actions

  // Define a template for blog post
  const blogPost = path.resolve(`./src/templates/blog-post.js`)

  // Get all markdown blog posts sorted by date
  const result = await graphql(
    `
      {
        allMarkdownRemark(sort: { frontmatter: { date: DESC } }, limit: 1000) {
          nodes {
            fields {
              slug
            }
            frontmatter {
              title
            }
          }
        }
      }
    `
  )

  if (result.errors) {
    reporter.panicOnBuild(
      `There was an error loading your blog posts`,
      result.errors
    )
    return
  }

  const posts = result.data.allMarkdownRemark.nodes

  // Create blog posts pages
  // But only if there's at least one markdown file found at "content/blog" (defined in gatsby-config.js)
  // `context` is available in the template as a prop and as a variable in GraphQL

  if (posts.length > 0) {
    posts.forEach((post, index) => {
      const previous = index === posts.length - 1 ? null : posts[index + 1]
      const next = index === 0 ? null : posts[index - 1]

      createPage({
        path: post.fields.slug,
        component: blogPost,
        context: {
          slug: post.fields.slug,
          previous,
          next,
        },
      })
    })
  }
}
Enter fullscreen mode Exit fullscreen mode

It uses server-side rendering and code splitting to deliver fast initial load times and smooth navigations. It also includes optimized image loading and automatic asset optimization to further improve the performance of your site.

Gatsby.js also offers a rich developer experience with features such as hot reloading, error debugging, and integration with popular tools and libraries. You can also use Gatsby’s plugin system to extend the functionality of your site with features such as analytics, SEO, or social media integration.

Gatsby.js also provides a flexible and powerful routing system that allows you to define the routes and corresponding pages of your site. You can create static pages or use dynamic routes to render different content for different URLs.

In addition to its core features, Gatsby.js has a vibrant and active community that maintains a wide variety of plugins and themes to help you build your site. You can use these resources to quickly add functionality or customize the appearance of your site.

How to start?

To setup gatsby project you can choose from Gatsby Starter Library which provides multiple starter projects with different frameworks integration out of the box.https://www.gatsbyjs.com/starters/ or we can you gatsby’s Quick Start Guide https://www.gatsbyjs.com/docs/quick-start/

Gatsby also have a next.js like approach for routing where we create a .js files in pages directory and export default the React component and then that component will be exposed to /<filename> route. In addition to this we can export a Head function from the file and return from that function will be injected to head tag of the page.

I have used Gatsby to create [this](codeentity.tech] blog site.

Why Gatsby?

Gatsby is all about speed: well-optimized websites with great SEO and performance and great ramp-up speed to build the app. It generates static HTML in advance, which can subsequently be stored on CDNs (Content Delivery Network) across the globe to facilitate quicker access.

One best thing I like about gatsby is its plugin ecosystem where you can get a plugin for almost anything.

From transforming markdown to html, adding _target to external routes. Ahead caching internal routes created by markdown, Adding custom meta tags, Generating RSS Feed you will get a plugin for the task you want to do or to extend its functionality.

Overall, Gatsby.js is a powerful and flexible tool for building fast and modern websites with React. Whether you are building a blog, portfolio, or e-commerce site, Gatsby.js has the tools and resources you need to create a high-performing and scalable site.

5. Remix.run

Remix is fullstack React frameworks similar to next.js but with its own unique features and benefits. Originally offered as a paid subscription service, the creators of Remix announced inOctober 2021 that the framework would be made open source.

One key feature of Remix is its focus on server-side rendering (SSR). This means that the backend and frontend of an application can be built using a single Remix app. Instead of fetching data on the frontend and rendering it on the screen, as is the case with vanilla React, Remix fetches data on the backend and serves the HTML directly to the user. This approach has the benefit of minimizing the amount of JavaScript that is required on the client side, resulting in faster page loads and a more efficient user experience.

But wait next is also doing same thing so what’s the difference. Why would I use Remix instead of Next.

Well Co-Founder of Remix Ryan Florence has written a detailed blog on this topic. You can read it here.

In this blog he has listed following advantages of using Remix over Next.

  • Remix is as fast or faster than Next.js at serving static content
  • Remix is faster than Next.js at serving dynamic content
  • Remix enables fast user experiences even on slow networks
  • Remix automatically handles errors, interruptions, and race conditions, Next.js doesn’t
  • Next.js encourages client side JavaScript for serving dynamic content, Remix doesn’t
  • Next.js requires client side JavaScript for data mutations, Remix doesn’t
  • Next.js build times increase linearly with your data, Remix build times are nearly instant and decoupled from data
  • Next.js requires you to change your application architecture and sacrifice performance when your data scales
  • We think Remix’s abstractions lead to better application code

One of the standout features of Remix is its support for nested routing. Nested routing refers to the idea of linking segments of the URL to the component hierarchy in the user interface. This has a number of benefits, as it allows developers to use the URL to control things like which layouts are rendered on the page, which JavaScript bundles are loaded, and what data dependencies those layouts have.

In contrast to some web applications that fetch data inside of components, which can result in slower page loads and a less smooth user experience, Remix loads data in parallel on the server and sends a fully formed HTML document to the client. This helps to improve the performance and efficiency of the application, as it minimizes the amount of data that needs to be transferred over the network and reduces the number of requests that need to be made.

You can follow https://remix.run/docs/en/v1/tutorials/blog this blog to setup the remix project.

6. Create React App

This one is the most commonly used tool on the list, but probably the last choice for a real-world production application.

Create React App is a command-line tool that allows you to quickly create and set up a new React application. It is developed and maintained by the React team and is the easiest way to create a new React application.

Using Create React App, you can create a new React application with just a few commands. It will automatically set up a development environment for you, including installing the necessary dependencies, configuring Webpack and Babel, and creating a development server.

One of the key benefits of Create React App is its simplicity. It abstracts away many of the complexities of setting up a React application, allowing you to focus on building your application instead of worrying about the underlying configuration.

Create React App will abstract the config and provide support of

  • Importing svg as component
  • Sass, Just need to install sass compiler.
  • Testing with Jest and React Testing Library.
  • Latest React Features like using React.lazy for code splitting.

Create React app is good option if creating admin dashboards where seo is not important and focus is on shipping product quickly instead of website optimization.

To create a new react app follow these steps

npx create-react-app my-app
cd my-app
npm install
npm start
Enter fullscreen mode Exit fullscreen mode

Create React App also provides option to add typescript and to change package manager to yarn instead of npm.

npx create-react-app my-app --template typescript
Enter fullscreen mode Exit fullscreen mode

This command will generate a typescript project.

In addition, the structure of a React app created with Create React App is consistent across projects, which makes it easier to switch between different React projects and understand how they are organized.

7. Vite

Vite is a modern build tool for JavaScript applications that allows you to quickly set up and develop a new project. It is designed to be fast and lightweight, making it an excellent choice for building React applications.

I personally prefer vite over cra as dev build time is too fast in vite. Around 10x fast.

Why Vite is fast

At its core, Vite does 2 things

  1. Serve your code locally during development.
  2. Bundle your Javascript, CSS and other assets together for production.

There are other tools(bundlers) that do the same thing, such as webpack, Parcel and Rollup, so what makes Vite different?

The problem with the tools mentioned above is that they have to build everything on every save, and if you have a very large application, that could take several minutes every time you save, even with Hot reloading in some frameworks, the update speed gets significantly slower as you add more code and dependencies to the app.

Vite has taken a different approach to this, kind of a reverse approach. Vite starts the server right away, takes the dependencies that don’t change often, and pre-bundles them using esbuild.

Vite uses route-based code-splitting to figure out what parts of the code actually need to be loaded, and doesn’t have to pre-bundle everything.

Vite serves the source code using native ES Module support in modern browsers. This lets the browser take the job of bundling in development, which consequently makes your code to load instantly, no matter how large the app is.

It also supports Hot Module Replacement for an extremely fast feedback loop during development.

When building for production, Vite uses Rollup under the hood, so you don’t have to worry about configuring it.

Creating a Project with Vite

To create a Vite application, open your terminal and navigate to the folder where you want to save the Vite program. Then run this command:

npm create vite@latest

You’ll be prompted to select a framework and a variant(template). In our case, we’ll be using React, so select React.

You can also directly specify the template you want to use and the project name in one single line:

npm create vite@latest react-app --template react

Next, run the following commands in the terminal

cd react-app
npm install
npm run dev
Enter fullscreen mode Exit fullscreen mode

Running the above command will start the development server. Then open your browser and enter http://localhost:3000.

Vite is faster then cra but is relatively new and don’t have that much community compared to cra. But it’s a good option if you are creating a side project in react as it comes with various templates and also support server side rendering.

Apart from react you can generate projects in several other frameworks also. https://vitejs.dev/guide/#trying-vite-online

Conclusion

There we go! We’ve looked at 7 different methods for generating a React Project. Each with its own pros and cons. Now that you have a better understanding of the options available to you, you can choose the best method for creating your next big thing. I hope this article was helpful in your decision-making process.

Top comments (0)