Next.js File Conventions: page.js
Last Updated :
14 Aug, 2024
Next.js File Conventions are practices and rules for organizing files in a Next.js application to manage routing and components efficiently. In these conventions, the page.js file represents a specific route in the application, where each file in the pages or app directory corresponds to a route.
This convention helps in defining page-level components and their rendering logic, supporting both server-side and client-side rendering.
Page.js File
In Next.js, page.js files are used to define the content and layout of individual pages in your application. Each page.js file corresponds to a route in your application, with its location in the src/app directory reflecting the route structure. This file typically exports a React component that renders the page content. Next.js uses this file to handle server-side rendering, static site generation, or client-side rendering based on your configuration and data fetching methods.
Syntax
const HomePage = () => (
<div>
<h1>Welcome to the Home Page</h1>
</div>
);
export default HomePage;
Dynamic Routing and Parameters
The page.js file can manage dynamic routes and parameters.
Example: In a file like app/blog/[slug]/page.tsx, you can use TypeScript to define the route and handle dynamic segments.
export default function DynamicPage({
params,
searchParams,
}: {
params: { slug: string },
searchParams: { [key: string]: string | string[] | undefined }
}) {
return <h1>Dynamic Content for {params.slug}</h1>;
}
Steps to Implement page File Convention in Next JS
Step 1: Create a Next.js application using the following command.
npx create-next-app@latest gfg
Step 2: It will ask you some questions, so choose as the following.
SetupStep 3: After creating your project folder i.e. gfg, move to it using the following command.
cd gfg
Folder Structure
Project StructureDependencies
"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.2.5"
}
we are using a page.js file in a Next.js application to create a dynamic home page with interactive features. The page includes a green h1 heading and an h3 heading for context. It also features a button that, when clicked, updates the displayed text using React's useState hook. The use client directive is used to enable client-side functionality in this component.
Example: The below example demonstrates the use of File Conventions: page.js.
JavaScript
// src/app/page.js
"use client";
import React, { useState } from 'react';
const HomePage = () => {
const [text, setText] = useState("Click the button to change this text.");
const handleClick = () => {
setText("Text has been changed!");
};
return (
<div style={{ padding: '20px' }}>
<h1 style={{ color: 'green' }}>GeeksforGeeks</h1>
<h3>Next.js File Conventions: page.js</h3>
<p>{text}</p>
<button onClick={handleClick} style={{ padding: '10px', fontSize: '16px' }}>
Change Text
</button>
</div>
);
};
export default HomePage;
To run the Application open the terminal in the project folder and enter the following command:
npm run dev
Output
Next.js File Conventions: page.jsRendering Behavior of page.js
Next.js offers various ways to render pages. The `page.js` file handles Client-Side Rendering (CSR) by updating content in the browser, Server-Side Rendering (SSR) by generating pages on the server for each request, and Static Site Generation (SSG) by pre-rendering pages at build time for faster loading.
Client-Side Rendering (CSR)
- How page.js Handles CSR: In CSR, the page is rendered in the browser with JavaScript. After the initial HTML loads, the rest of the page updates and data are managed on the client side. This method is ideal for pages that need real-time interactions and dynamic updates.
- Transitioning Between Pages: Next.js ensures smooth client-side navigation without reloading the entire page. Its internal routing system updates the page content dynamically as you navigate through different sections.
Server-Side Rendering (SSR)
- SSR with page.js: With SSR, Next.js generates the HTML for your page on the server for each request, ensuring that the page is always up-to-date when it reaches the user. You can enable SSR in page.js using the getServerSideProps function.
- When to Use SSR vs. CSR: Use SSR when you need the page to show the latest data or want the content rendered on the server before it reaches the user. Use CSR for pages that are less reliant on real-time data or where client-side interactions are more crucial.
Static Site Generation (SSG)
SSG generates the page's HTML at build time rather than request time. By using getStaticProps, you fetch data and create static pages that are served quickly to users. This approach is best for pages with content that doesn’t change often.
Benefits of SSG:
- Faster Load Times: Static pages are served quickly from a CDN, leading to faster page loads.
- Less Server Load: Pre-built pages reduce the server's workload during runtime.
- Better SEO: Pre-rendered pages are fully visible to search engines, enhancing your site's SEO.
Key Points to remember
- File Location: The location of the page.js file determines its route. For example, src/app/about/page.js corresponds to the /about route.
- Component Export: Each page.js file should export a React component.
- Rendering: Next.js uses the page.js file to determine how to render the page, whether server-side, statically, or client-side.
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. "Hello, World!" Program in ReactJavaScriptimport React from 'react'; function App() {
6 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides DOM-specific methods to interact with and manipulate the Document Object Model (DOM), enabling efficient rendering and management of web page elements. ReactDOM is used for: Rendering Components: Displays React components in the DOM.DOM Manipulation: Al
2 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsIn lists, React makes it easier to render multiple elements dynamically from arrays or objects, ensuring efficient and reusable code. Since nearly 85% of React projects involve displaying data collectionsâlike user profiles, product catalogs, or tasksâunderstanding how to work with lists.To render a
4 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. When rendering a list, you need to assign a unique key prop to each element in th
4 min read
Components in React
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects