NextJS Interview Questions - GeeksForGeeks - Jan 2024 Flashcards
What is Next JS?
Next JS is an open-source web development React-based framework created by Vercel, which is famous for its unique features such as Server-side rendering and enhanced SEO. It has some additional features such as data fetching utilities, dynamic API routes, optimized builds, etc. It is a framework built upon React, Webpack, and Babel.
How Next is different from other JavaScript frameworks?
Next.js is a JavaScript framework that is primarily designed for building React applications. Here are some key ways in which Next JS differs from other JavaScript frameworks:
Server-Side Rendering (SSR): One of the significant distinctions of Next JS is its built-in support for server-side rendering. This allows pages to be rendered on the server rather than the client, providing benefits like improved SEO and faster initial page loads.
Automatic Code Splitting: Next.js automatically splits the JavaScript code into smaller chunks, allowing for efficient loading of only the necessary code for a particular page.
API Routes: Next.js makes it easy to create API routes within the same project, simplifying the development of backend functionality alongside the frontend.
Built-in Image Optimization: The next/image component provides built-in support for image optimization, handling tasks like lazy loading and responsive images without the need for additional configuration.
Easy Deployment: Next.js simplifies the deployment process with various options, including static site hosting, serverless deployment, and more. This ease of deployment is not always as straightforward in other frameworks.
How can you install Next JS?
Below is the step by step process of installing the Next JS:
Steps to Install the Next JS:
Step 1: Node JS should be already installed in the system.
Step 2: Now create the next js app using the below command:
npx create-next-app myapp
Step 3: Now switch to the project directory:
cd myapp
Step 4: Next JS app is initialized by updating the package.json:
{
“scripts”: {
“dev”: “next”,
“build”: “next build”,
“start”: “next start”
}
}
Write a Hello World Program in Next JS?
In Next.js, creating a “Hello World” program involves setting up a simple React component within a file in the app directory. Here’s a basic example:
// page.js
import React from ‘react’;
const HomePage = () => {
return (
<div>
<h1>Hello, Next.js!</h1>
</div>
);
};
export default HomePage;
Mention some features of Next JS.
Next.js is a powerful React framework that offers various features to simplify and enhance the development of web applications. Here are some key features of Next.js:
Server-Side Rendering (SSR): Next.js allows server-side rendering, improving initial page load performance by rendering HTML on the server and sending it to the client.
Static Site Generation (SSG): Next.js supports static site generation, enabling the pre-rendering of pages at build time, resulting in faster loading times and better SEO.
File System-Based Routing: The routing system is based on the file structure of the “pages” directory, making it intuitive and easy to organize code.
Automatic Code Splitting: Next.js automatically splits code into smaller chunks, loading only what’s necessary for each page. This enhances performance by reducing initial bundle sizes.
API Routes: Easily create serverless functions by defining API routes alongside your pages, simplifying the development of server-side logic.
What do you mean by SSR?
SSR stands for Server-Side Rendering. It’s a technique used in web development where the server processes the React or other JavaScript framework code and generates the HTML on the server side, sending the fully rendered HTML to the client’s browser.
Here’s a brief overview of the SSR process:
Request from Client: When a user makes a request to a server for a web page, the server receives the request.
Server-Side Processing: Instead of sending just a blank HTML shell or a minimal document, the server executes the JavaScript code associated with the requested page, fetches data if needed, and renders the complete HTML content on the server side.
Sending Rendered HTML to Client: The fully rendered HTML, along with any necessary CSS and JavaScript, is sent as a response to the client’s browser.
Client-Side Hydration: Once the HTML is received by the browser, any JavaScript code needed for interactive elements or further client-side rendering is executed. This process is known as “hydration.”
What are the benefits of using Next JS?
Next.js is a popular React framework that brings several benefits to web development. Here are some of the key advantages of using Next.js:
Server-Side Rendering (SSR):
Next.js supports server-side rendering out of the box. This means that pages can be rendered on the server and then sent to the client, providing better performance and SEO as search engines can crawl the fully rendered content.
Static Site Generation (SSG):
Next.js allows for static site generation, where pages can be pre-built at build time. This can significantly improve performance by serving static files directly from a CDN, reducing the load on servers and improving the user experience.
Automatic Code Splitting:
Next.js automatically splits the code into smaller chunks, allowing for efficient loading of only the necessary code for a particular page. This results in faster initial page loads and improved overall performance.
Built-in CSS Support:
Next.js provides built-in support for styling solutions, including CSS modules, styled-jsx, and support for CSS-in-JS libraries. This allows developers to choose their preferred styling approach without the need for additional configuration.
API Routes:
Next.js allows you to create API routes easily, enabling the development of serverless functions. This can be useful for handling backend logic without the need for a separate server.
What is DOM?
DOM stands for Document Object Model. It is a programming interface for web documents. The DOM represents the structure of a document as a tree of objects, where each object corresponds to a part of the document, such as elements, attributes, and text.
Here are some key points about the Document Object Model:
Tree Structure: The DOM represents an HTML or XML document as a tree structure. Each element, attribute, and piece of text in the document is represented by a node in the tree.
Object-Oriented: The DOM is an object-oriented representation of a document. Each node in the tree is an object, and these objects can be manipulated using programming languages like JavaScript.
Dynamic: The DOM is dynamic, meaning it can be modified programmatically. Developers can use scripting languages like JavaScript to manipulate the content, structure, and style of a document in real-time.
Interface for Web Browsers: The DOM serves as an interface between web browsers and web documents. Browsers use the DOM to render and display web pages, and developers use it to interact with and modify the content of those pages.
How does Next JS handle client-side navigation?
Next.js uses a client-side navigation approach that leverages the HTML5 History API. This enables smooth transitions between pages on the client side without a full page reload. The framework provides a built-in Link component that facilitates client-side navigation, and it supports both traditional anchor (<a>) tags and programmatically navigating through the next/router module.</a>
Here’s an overview of how Next.js handles client-side navigation:
Link Component:
The Link component is a core part of client-side navigation in Next.js. It is used to create links between pages in your application.
Using the Link component, when users click the link, Next.js intercepts the navigation event and fetches the necessary resources for the new page without triggering a full page reload.
import Link from ‘next/link’;
const MyComponent = () => (
</a><a>Go to another page</a>
);
Programmatic Navigation:
In addition to using the Link component
import { useRouter }
from ‘next/router’;
const MyComponent = () => {
const router = useRouter();
const handleClick = () => {
router.push(‘/another-page’);
};
return (
Go to another page
);
};”
Explain the concept of dynamic routing in Next JS:
Dynamic routing in Next.js refers to the ability to create routes for pages with dynamic parameters, allowing you to build pages that can handle different data or content based on the values of these parameters. Instead of creating a separate page for each variation, you can use a single page template and dynamically generate content based on the provided parameters.
What is meant by Styled JSX in Next JS?
We employ the Styled JSX CSS-in-JS library to create encapsulated and scoped styles for styling Next JS components. This ensures that the styles introduced to a component have no impact on other components, enabling seamless addition, modification, and removal of styles without affecting unrelated parts of the application.
Is Next JS backend, frontend, or full-stack?
Next JS is considered a full-stack framework, offering the capability to render content on both the client-side and server-side. This feature is particularly valuable in the context of React, as React by itself primarily focuses on frontend development without built-in server-side rendering capabilities.
Difference between the pre-rendering types available in Next JS.
Static Generation (SG)
Server-Side Rendering (SSR)
Generation Timing
HTML is generated at build time.
HTML is generated on each request.
Reuse of HTML
The pre-generated HTML can be reused on every request.
HTML is generated anew for each request.
Recommendation
Recommended for performance and efficiency.
Suitable for cases where content changes frequently or cannot be determined at build time.
Export Methods:
Export the page component or use ‘getStaticProps‘
Export ‘getServerSideProps‘
Build Time Dependency:
Less dependent on server resources during runtime.
Depends on server resources for generating content dynamically.
Performance
Typically faster as HTML is pre-generated.
Can introduce higher server load due to on-the-fly HTML generation.
Caching
Easily cache static HTML.
Requires server-side caching mechanisms.
Scalability
Scales well as static content can be served efficiently.
May require additional server resources to handle dynamic content generation.
What is client-side rendering, and how does it differ from server-side rendering?
Client-side rendering (CSR) involves rendering a web page on the client’s browser through JavaScript after the initial delivery of HTML, CSS, and JavaScript from the server. The primary distinction between SSR and CSR lies in the fact that SSR transmits a completely rendered HTML page to the client’s browser, whereas CSR delivers an initially empty HTML page that is then populated using JavaScript.
How do you pass data between pages in a Next JS application?
Next JS provides several ways to pass data between pages in a Next JS application, including URL query parameters, the Router API, and state management libraries like Redux or React Context. You can also use the getServerSideProps function to fetch data on the server and pass it as props to the page component.
What is the difference between getServerSideProps & getStaticProps functions in Next.js?
getServerSideProps
getStaticProps
Timing of Execution
Executes on every request.
Executes at build time.
Server-Side vs. Static Generation
Used for server-side rendering (SSR).
Used for static site generation (SSG).
Dynamic vs. Static Content
Suitable for pages with frequently changing or dynamic content.
Ideal for pages with relatively static content that can be determined at build time.
Dependency on External Data
Fetches data on every request, allowing for real-time updates.
Fetches data at build time, so the data is static until the next build.
Use of context Object
Receives a context object containing information about the request.
Also receives a context object, but primarily used for dynamic parameters.
Error Handling
Handles errors during each request.
Errors during data fetching result in a build-time error.
Return Object Structure:
Returns an object with a props key.
Returns an object with a props key, but may also include a revalidate key for incremental static regeneration.
Performance Considerations
Tends to be slower due to on-the-fly data fetching on each request.
Generally faster as data is fetched at build time, reducing server load.
What is the purpose of the getStaticPaths function in Next JS?
The getStaticPaths
function is employed to create dynamic paths for pages that involve dynamic data. This function is invoked during the build process, allowing the generation of a list of potential values for the dynamic data. The data produced by getStaticPaths
is subsequently utilized to produce static files for each conceivable value.
What is the purpose of the useEffect hook in React, and how does it relate to Next JS?
The useEffect hook is used to perform side effects in a functional component, such as fetching data from an API or updating the document title. In Next JS, the useEffect hook can be used to perform client-side data fetching using the fetch API or third-party libraries like Axios or SWR.
What do you understand by code splitting in Next JS?
In general, code splitting stands out as one of the most compelling features provided by webpack. This functionality allows us to divide our code into multiple bundles, which can be loaded either on-demand or in parallel. Its primary purpose is to create smaller bundles and enables us to manage the prioritization of resource loading, ultimately contributing significantly to improved load times.
There are mainly three approaches to code splitting:
Entry Points: Employed for manual code splitting by configuring entry points.
Avoiding Redundancy: Utilizes entry dependencies or the SplitChunksPlugin to deduplicate and divide chunks.
Dynamic Imports: Achieves code splitting through inline function calls within modules.
Its primary purpose is to facilitate the creation of pages that never load unnecessary code.
How do you handle data fetching in Next JS?
In Next.js, data retrieval from an external API or database can be achieved using the built-in functions, namely, getStaticProps
or getServerSideProps
. The getStaticProps
function fetches data during the build process and provides it as props to the page, whereas getServerSideProps
fetches data for each incoming request. Alternatively, client-side data fetching libraries such as axios
or fetch
can also be employed in conjunction with the useEffect
or useState
hooks.