Next.js: The React Framework of the Future
porGabriel Dürr M., São Paulo - SP
Next.js is currently considered one of the most popular frameworks on the market. Thanks to its speed and robustness of resources, the framework is also known for its versatility and flexibility, very powerful and viable for creating e-commerce sites, landing pages, marketing sites, static websites and with a focus on SEO – from creation to guarantee scalability. Next.js offers resources for creating APIs within the project itself, caching, image optimization, etc.
Initial setting:
Create a Next.js project:
npx create-next-app@latest
With TypeScript add the flag --ts
npx create-next-app@latest --ts
NOTE: There is still the option to use a package manager (NPM, Yearn, PNPM ...):
Development flow:
The creation of pages happens in a very simple way, all files inside the pages folder (with the exception of config files) are transformed into pages/routes.
And all files inside the API folder are turned into API routes.
Styling with CSS Modules:
In addition to Global styling, we have a resource called CSS modules that allows us to create styling at the component level, that is, the style is applied only within the scope of the component, without having to worry about class name conflicts in our application.
It's a big plus to add a pre-processor like SASS to work together with css modules and we create cascading and more complex styles...
First we must create a folder that will contain the index of the component, and create a styling file in the format file name + module.css extension, getting this way for example: input.module.css
- By convention and organization we use the same name as the component, adding only the module.css extension
- We create the styles, having each style with the class syntax:
.bg {
display: flex;
justify-content: center;
margin: 5% auto;
width: 600px;
height: 300px;
color: #fff;
background-color: #000;
}
- We import the styling file in the default export format, a convention is to use the name styles, and we use the component's styling through React's className property, accessing the styling prop created in the module.css file.
import styles from "./box-container.module.css";
type BoxContainerProps = {
children?: ReactNode;
};
export const BoxContainer = ({ children }: BoxContainerProps) => {
return <div className={styles.bg}>{children}</div>;
};
- Final result:
Main features of Next.js:
- Server-side rendering (SSR)
import { GetServerSideProps } from "next";
export const getServerSideProps: GetServerSideProps = async () => {
const fetchUserApi = {
name: "Gabriel",
alias: "gbdx",
age: 23,
};
return {
props: {
fetchUserApi,
},
};
};
When using the SSR function, it will be executed with each request made on the client by the user, that is, whenever the page is opened/updated, the next.js server will look for data from an API, for example, and provide these new application data.
We must use this function in cases where there is a real need, such as blocking content that can only be viewed with special access. For data that does not need to be updated with each request, we can take advantage of the generation of static pages and thus have incomparable gains in terms of page loading.
- Generation of static pages (SSG)
import { GetStaticProps } from "next";
export const getStaticProps: GetStaticProps = async ({ params }) => {
const res = await fetch(`https://site-deployed/page/${params.id}`);
const data = await res.json();
return {
props: {
data,
},
};
};
This functionality is certainly the icing on the next.js cake, with it we can generate pre-rendered static pages at build time, and thus they will be rendered by the client without the user waiting for it to load 🤩. But if there are data updates, the content is only reflected on the page by doing a new build.
- Generation of static pages incrementally (ISG)
import { GetStaticProps } from "next";
export const getStaticProps: GetStaticProps = async ({ params }) => {
const res = await fetch(`https://site-deployed/page/${params.id}`);
const data = await res.json();
const thirtySeconds = 30 * 1000;
return {
props: {
data,
},
revalidate: thirtySeconds,
};
};
We can generate static pages, with content being updated incrementally every period of time. That is, it will update automatically without having to do a new build so that the new data is reflected on the page. For this, we use the revalidate prop, defining the time in seconds, and next.js is responsible for updating the content whenever it reaches the defined time count
- Using dynamic static pages with: getStaticPaths + Static Site Generation (SSG)
import { GetStaticPaths } from "next";
export const getStaticPaths: GetStaticPaths = async () => {
const res = await fetch("https://site-deployed/page");
const data = await res.json();
const paths = data.map(post => ({
params: { id: post.id.toString() },
}));
return {
paths,
fallback: false,
};
};
When we need to generate static pages that are accessed dynamically through url parameters, we need to inform Next.js of all the existing routes of the application, so that when we perform the build it will create the route for all pages.
To solve this problem, we use the getStaticPaths function that will be responsible for generating all the routes. This function should return an object with a property called params, and this property contains an array/list of objects. Inside each object we provide the name of the route for the property which is the same name we put in the dynamic route file, like in this example: [uid] , which could be called [slug], etc.
We can retrieve the value typed in the url parameter, in the getStaticProps function and use a filter in our fetch that will fetch and generate all static pages for the uuid/slug of getStaticPaths. So we will have all pages with all routes defined statically, and this page will be displayed dynamically according to its route.
import { GetStaticProps } from "next";
export const getStaticProps: GetStaticProps = async ({ params }) => {
const queryApiWithParamsId = params.id;
const res = await fetch(`https://site-deployed/page/${queryApiWithParamsId}`);
const data = await res.json();
return {
props: {
data,
},
};
};
Conclusion
In summary, Next.js is an essential tool for developing more sophisticated React applications as it offers advanced features like SSR and SSG. With its framework optimized for scalable application development, Next.js makes building web applications even easier and more productive.
If you are looking for an efficient way to create powerful React applications, visit the official NEXT.Js documentation and evolve with the framework.