0% found this document useful (0 votes)
23 views12 pages

React - Js and Next - Js Interview Questions PDF

Uploaded by

dineshkumarnov96
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views12 pages

React - Js and Next - Js Interview Questions PDF

Uploaded by

dineshkumarnov96
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

React and Next.

js Interview Questions

1. How will you perform form validation in React?


Form validation in React ensures data integrity and provides a better user experience by preventing invalid submissions and guiding
users with helpful error messages. Here’s a breakdown of the common approaches:
a) Built-in HTML5 Validation:
• HTML Attributes: Leverage HTML5 attributes like required, pattern, minlength, maxlength, etc., directly in your HTML
elements. These attributes provide basic validation checks without requiring additional JavaScript code.
<form>
<input type="text" required placeholder="Enter your name" />
<input
type="email"
pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$"
required
placeholder="Enter your email"
/>
<button type="submit">Submit</button>
</form>

• Browser Support: This method relies on browser support for HTML5 validation, so it might not work perfectly across all
browsers.
b) Custom JavaScript Validation:
• Inline Validation: Perform validation directly within the component’s state and update error messages based on input changes.
import { useState } from "react";

function MyForm() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [errors, setErrors] = useState({});

const handleSubmit = (event) => {


event.preventDefault();
const newErrors = {};
if (!name) {
newErrors.name = "Name is required";
}
if (!email || !isValidEmail(email)) {
newErrors.email = "Please enter a valid email";
}
setErrors(newErrors);
};

const isValidEmail = (email) => {


// Your email validation logic
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
};

return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
{errors.name && <span className="error">{errors.name}</span>}
</div>
<div>
<label htmlFor="email">Email:</label>
<input
type="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
{errors.email && <span className="error">{errors.email}</span>}
</div>
<button type="submit">Submit</button>
</form>

Page. 1 [email protected]
);
}

• Explanation:
– The component manages input values in its state (name, email).
– Validation rules are defined in functions (e.g., isValidEmail).
– Error messages are displayed based on validation results using errors.name and errors.email.
c) Real-time Validation:
• Event Handlers: Use the onChange event handler to validate input values as the user types, providing immediate feedback.
import { useState } from "react";

function MyForm() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [errors, setErrors] = useState({});

const handleNameChange = (event) => {


setName(event.target.value);
if (!event.target.value) {
setErrors({ ...errors, name: "Name is required" });
} else {
setErrors({ ...errors, name: "" });
}
};

// Similar logic for email validation

return <form>{/* ... form elements ... */}</form>;


}

• Explanation:
– Each input field has an onChange handler (e.g., handleNameChange).
– The handler updates the state and the errors object, displaying error messages immediately in the UI.
d) Libraries (Formik, React Hook Form):
• Formik: A popular library that simplifies form management, including validation, submission, and state management.
• React Hook Form: Another great option that focuses on performance and minimizes boilerplate code.
Example with Formik:
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";

function MyForm() {
const validationSchema = Yup.object().shape({
email: Yup.string().email("Invalid email format").required("Required"),
password: Yup.string()
.required("Required")
.min(6, "Password must be at least 6 characters"),
});

return (
<Formik
initialValues={{ email: "", password: "" }}
validationSchema={validationSchema}
onSubmit={(values) => {
console.log("Form submitted:", values);
}}
>
{({ errors, touched }) => (
<Form>
<Field type="email" name="email" />
<ErrorMessage name="email" component="div" />

<Field type="password" name="password" />


<ErrorMessage name="password" component="div" />

<button type="submit">Submit</button>
</Form>
)}
</Formik>
);
}

• Explanation:
– Formik manages the form state and validation.
– Yup is used to define validation schemas.

Page. 2 [email protected]
– Field components represent form inputs.
– ErrorMessage components display validation errors.

2. What is Reconciliation in React?


Reconciliation is React’s core algorithm for updating the DOM efficiently. It is a lightweight process that compares a virtual
representation of the DOM (virtual DOM) with the previous version to determine the minimal changes required to update the actual
DOM. This minimizes unnecessary DOM manipulations, leading to better performance and a smooth user experience.
Here’s how it works:
1. Virtual DOM: When React renders a component, it creates a virtual DOM representation – a lightweight JavaScript object that
mimics the structure of the actual DOM.

2. Change Detection: When a component’s state or props change, React triggers reconciliation. It compares the current virtual
DOM with the previous version.
3. Minimal Updates: React identifies the specific differences (e.g., changes in text content, attribute updates, or added/removed
elements) between the two virtual DOMs.
4. DOM Updates: React only updates the necessary parts of the actual DOM, avoiding unnecessary DOM manipulations that would
slow down the rendering process.

Example:
• Imagine you have a simple counter component that increments the count.
• When the count is updated, React doesn’t re-render the entire component; instead, it only changes the text content of the element
displaying the count.
Benefits of Reconciliation:
• Improved Performance: Minimizes DOM manipulations, resulting in faster rendering and better user experience.
• Efficient Updates: Only updates the necessary elements, reducing the amount of work done by the browser.
• Virtual DOM: The virtual DOM allows React to perform diffing algorithms efficiently and determine the smallest set of changes to
make.

3. What is Memoization and how is it used in React?


Memoization is a technique for optimizing performance by caching the results of expensive function calls. In React, it’s particularly
helpful for preventing unnecessary re-renders of components.
How it works:
1. Caching: When a memoized function is called with the same set of arguments, it retrieves the cached result instead of executing
the function again.
2. Dependency Tracking: Memoization often involves a mechanism for tracking dependencies (e.g., props or state variables). If
any of the dependencies change, the cached result is invalidated, and the function is re-executed.
Example:
import { React, memo } from "react";

function MyExpensiveComponent(props) {
// Assume this function performs complex calculations
// or has heavy DOM manipulations
const result = doExpensiveCalculation(props.data);
return <div>{result}</div>;
}

const MemoizedComponent = memo(MyExpensiveComponent);

function App() {
// ...
return (
<div>
<MemoizedComponent data="some data" />
{/* ... other components ... */}
</div>
);
}

• Explanation:
– MyExpensiveComponent performs some expensive calculation.
– By using memo, we memoize the component (MemoizedComponent).
– If props.data doesn’t change, the component will not re-render, saving computation time.
Use Cases:

Page. 3 [email protected]
• Components with Expensive Operations: Memoize components that perform complex computations or have heavy DOM
operations.
• Components with Frequent Re-renders: Memoize components that are re-rendered frequently, especially if they are nested
deeply within the component tree.
• Function Calls: Memoize functions that are called repeatedly with the same arguments.

4. Explain the 5 React hooks and their use cases:


React Hooks are functions that let you “hook” into React features (like state, lifecycle, and context) from functional components. They
provide a way to manage component logic without using classes.
a) useState:
• Purpose: Manage the internal state of a functional component.

• Usage:

– const [stateVariable, setStateFunction] = useState(initialValue);


– stateVariable holds the current state value.
– setStateFunction is used to update the state.
• Example:
import { useState } from "react";

function Counter() {
const [count, setCount] = useState(0);

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

b) useEffect:
• Purpose: Perform side effects in functional components, such as fetching data, setting up subscriptions, or manipulating the
DOM.

• Usage:

– useEffect(callbackFunction, dependencyArray);
– callbackFunction: The function that contains the side effects.
– dependencyArray: An optional array of dependencies. The effect will run after every render if the dependency array is
empty ([]) or whenever any of the dependencies change.
• Example:

import { useEffect, useState } from "react";

function DataFetcher() {
const [data, setData] = useState(null);

useEffect(() => {
fetch("https://api.example.com/data")
.then((response) => response.json())
.then((data) => setData(data));
}, []); // Fetch data only once on mount

return <div>{data && <p>Data: {data.name}</p>}</div>;


}

c) useContext:
• Purpose: Access values from the React Context API.

• Usage:

– const value = useContext(Context);


– Context: The React Context object.
• Example:

import React, { createContext, useContext, useState } from "react";

const ThemeContext = createContext("light");

function ThemeProvider({ children }) {


const [theme, setTheme] = useState("light");

Page. 4 [email protected]
return (
<ThemeContext.Provider value={theme}>{children}</ThemeContext.Provider>
);
}

function MyComponent() {
const theme = useContext(ThemeContext);

return (
<div style={{ backgroundColor: theme === "dark" ? "black" : "white" }}>
{/* ... */}
</div>
);
}

function App() {
return (
<ThemeProvider>
<MyComponent />
</ThemeProvider>
);
}

d) useRef:
• Purpose: Create a persistent reference to a DOM element or any other value.

• Usage:

– const ref = useRef(initialValue);


– ref.current: Access the current value of the reference.
• Example:

import { useRef } from "react";

function FocusInput() {
const inputRef = useRef(null);

const handleClick = () => {


inputRef.current.focus(); // Focus on the input element
};

return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleClick}>Focus Input</button>
</div>
);
}

e) useCallback:
• Purpose: Memoize callback functions to prevent unnecessary re-renders when passed as props to child components.

• Usage:

– const memoizedCallback = useCallback(callbackFunction, dependencyArray);


– callbackFunction: The callback function you want to memoize.
– dependencyArray: An array of dependencies. If any dependency changes, the callback will be recreated.
• Example:

import { useState, useCallback } from "react";

function ParentComponent() {
const [count, setCount] = useState(0);

const handleClick = useCallback(() => {


setCount(count + 1);
}, [count]); // Memoize handleClick

return (
<div>
<ChildComponent handleClick={handleClick} />
{/* ... */}
</div>
);
}

function ChildComponent({ handleClick }) {

Page. 5 [email protected]
return <button onClick={handleClick}>Increment</button>;
}

5. What are Promises in JavaScript?


Promises are objects that represent the eventual result of an asynchronous operation. They provide a more structured and cleaner way
to manage asynchronous code compared to traditional callback-based approaches.
Key Features:
• Asynchronous Operations: Promises represent the result of operations that don’t immediately return a value, such as fetching
data from a server or performing time-consuming tasks.

• Three States: A promise can be in one of three states:

– Pending: The operation is still in progress.


– Fulfilled: The operation completed successfully, and the promise has a value.
– Rejected: The operation failed, and the promise has an error.
• .then(), .catch(), .finally(): Promises use these methods to handle the success (.then()) or failure (.catch()) of the
operation. The .finally() method is called regardless of whether the promise is fulfilled or rejected.

Example:
const fetchUserData = () => {
return new Promise((resolve, reject) => {
fetch("https://api.example.com/user")
.then((response) => response.json())
.then((data) => resolve(data))
.catch((error) => reject(error));
});
};

fetchUserData()
.then((data) => console.log("User data:", data))
.catch((error) => console.error("Error fetching user data:", error));

• Explanation:
– fetchUserData returns a Promise representing the result of fetching user data.
– Inside the promise constructor, the resolve function is called if the fetch operation succeeds, passing the data as an
argument.
– The reject function is called if there’s an error, passing the error object.
– The .then method handles the successful result, and .catch handles errors.

6. How do you handle asynchronous operations in JavaScript?


Asynchronous operations in JavaScript involve actions that don’t immediately return a result, often waiting for something to happen
(e.g., a network request, timer). Here are common ways to handle them:
a) Callbacks:
• How it works: Pass a function (the callback) as an argument to the asynchronous function. When the asynchronous operation
completes, the callback is executed with the result.

• Example:
function fetchData(url, callback) {
// Simulate asynchronous operation
setTimeout(() => {
callback("Data fetched from " + url);
}, 2000);
}

fetchData("https://api.example.com", (data) => {


console.log(data); // Output: "Data fetched from https://api.example.com"
});

b) Promises:
• How it works: Promises provide a more structured and cleaner approach to handling asynchronous operations. They represent
the eventual result of the operation and allow you to chain .then and .catch methods to handle success and failure cases.

• Example:
const fetchUserData = () => {
return new Promise((resolve, reject) => {
fetch("https://api.example.com/user")
.then((response) => response.json())
.then((data) => resolve(data))

Page. 6 [email protected]
.catch((error) => reject(error));
});
};

fetchUserData()
.then((data) => console.log("User data:", data))
.catch((error) => console.error("Error fetching user data:", error));

c) Async/Await:
• How it works: Async/Await is syntactic sugar for Promises, making asynchronous code look more synchronous. It simplifies
handling promises, making the code easier to read and write.

• Example:
async function fetchData(url) {
try {
const response = await fetch(url);
const data = await response.json();
console.log("Data:", data);
} catch (error) {
console.error("Error fetching data:", error);
}
}

fetchData("https://api.example.com/data");

7. What are the key features of Next.js?


Next.js is a React framework that helps build server-rendered React applications. Here are some of its key features:
• Server-Side Rendering (SSR):

– Benefits: Improved SEO, faster initial page load times, and better performance for applications with dynamic content.
– How it works: Next.js renders pages on the server before sending the fully formed HTML to the browser. This eliminates
the need for the browser to wait for JavaScript to execute before displaying content.
• Static Site Generation (SSG):
– Benefits: Super-fast page loads, perfect for content-focused websites, and excellent SEO.
– How it works: Next.js pre-renders pages as static HTML files during the build process. These files are served directly to
the browser, resulting in lightning-fast initial loads.
• Automatic Code Splitting:

– Benefits: Improved performance by only loading the necessary code for each page.
– How it works: Next.js automatically splits your code into smaller bundles, so users only download the code they need for
the current page.
• Built-in Routing:

– Benefits: Easy to manage URLs and handle navigation within your application.
– How it works: Next.js uses a file-based routing system, where each file in the pages directory represents a route.
• API Routes:

– Benefits: Build serverless APIs directly within your Next.js project, allowing you to create backend functionality without
setting up a separate server.
– How it works: Create files in the pages/api directory to define API routes.
• Data Fetching:

– Benefits: Simplified and efficient ways to fetch data for both SSR and SSG.
– How it works: Next.js provides getStaticProps for SSG and getServerSideProps for SSR to fetch data and pass it to the
components.
• Improved Development Experience:

– Benefits: Fast hot reloading, built-in support for TypeScript, and powerful debugging tools.

8. How does routing work in Next.js, and what’s the difference between page routing and app routing?
Next.js utilizes a file-based routing system, meaning the structure of your pages directory determines the routes in your application.
a) Page Routing (Traditional):
• File Structure: Files in the pages directory map directly to routes. For example:

– pages/index.js is the home page (/)


– pages/about.js is the about page (/about)
– pages/blog/[slug].js is a dynamic route for blog posts (e.g., /blog/my-post)
• Advantages:

Page. 7 [email protected]
– Simple setup.
– Suitable for static pages and content-focused websites.
– Good for SEO due to server-side rendering.
• Disadvantages:
– Less flexible for dynamic and interactive applications.
– Can be more complex to manage for large applications with many routes.
b) App Routing (New in Next.js 13):
• File Structure: Uses a new app directory for routing. Components nested within the app directory are rendered on the client-
side.

• Advantages:
– More dynamic and interactive experiences.
– Easier to manage for complex, stateful applications.
– Improved client-side hydration performance.
• Disadvantages:
– Requires a bit more setup compared to page routing.
– SEO might require some additional configuration for client-side rendered components.
Example:
• Page Routing:

– pages/blog/[slug].js maps to /blog/my-post


– This page is rendered on the server (SSR or SSG).
• App Routing:

– app/page.js is the root of your application.


– Components within the app directory are rendered on the client-side.
– app/blog/[slug]/page.js maps to /blog/my-post.

9. What are Higher Order Components (HOCs) in React?


Higher Order Components (HOCs) are functions that take a React component as input and return a new, enhanced component. They
provide a way to add functionality to components without modifying their original code.
How they work:
1. Input: A HOC takes a component as an argument.
2. Enhancement: The HOC adds features or functionality to the component.
3. Output: It returns a new, enhanced component that wraps the original component.
Example:
function withLogging(WrappedComponent) {
return function WithLoggingProps(props) {
console.log("Component rendering:", WrappedComponent.name);
return <WrappedComponent {...props} />;
};
}

const MyComponent = withLogging(function MyComponent(props) {


return <div>{props.message}</div>;
});

<MyComponent message="Hello, World!" />; // Output: "Component rendering: MyComponent"

• Explanation:
– withLogging is the HOC. It takes a component (WrappedComponent) and returns a new component (WithLoggingProps).
– WithLoggingProps logs a message before rendering the original component.

Use Cases:
• Code Reuse: Apply the same logic to multiple components without repeating code.
• Data Fetching: Fetch data for a component before rendering.
• Error Handling: Handle errors in a central place.
• Styling: Apply styles to a component.

10. What’s the difference between React and Next.js?


• React: A JavaScript library for building user interfaces. It provides the foundation for building components, managing state, and
rendering views.

Page. 8 [email protected]
• Next.js: A React framework that extends React’s core features, adding capabilities for server-side rendering, static site
generation, routing, data fetching, and other enhancements.
Key Differences:

Feature React Next.js


Purpose UI library React framework
Rendering Client-side rendering (by default) Server-side rendering (SSR) and Static Site Generation (SSG)
Routing Requires a routing library (e.g., React Router) Built-in routing
Data Requires manual data fetching (e.g., fetch, Built-in data fetching (getStaticProps, getServerSideProps)
Fetching axios)
Optimization Requires manual optimization (e.g., code Automatic code splitting, pre-rendering, and other built-in
splitting, caching) optimization features

In Essence: React provides the building blocks, while Next.js builds upon React to offer a framework with additional features and
optimizations.

11. Can you explain the React lifecycle?


The React lifecycle describes the different stages a component goes through from its creation to its destruction. It allows you to manage
component state, fetch data, perform side effects, and clean up after a component is no longer needed.
Lifecycle Methods:
• Mounting:

– constructor(): Initialize component state (only for class components).


– static getDerivedStateFromProps() : Update state based on new props (only for class components).
– render(): Render the component’s UI.
– componentDidMount(): Perform side effects after the component has mounted to the DOM (e.g., fetching data, setting up
subscriptions).
• Updating:

– static getDerivedStateFromProps() : Update state based on new props (only for class components).
– shouldComponentUpdate(): Determine if the component needs to re-render (only for class components).
– render(): Render the component’s UI.
– getSnapshotBeforeUpdate(): Capture state before a DOM update (only for class components).
– componentDidUpdate(): Perform side effects after a component has updated (e.g., updating data based on new props).
• Unmounting:
– componentWillUnmount(): Clean up any subscriptions or resources before the component unmounts (only for class
components).
– useEffect with a cleanup function: This is used in functional components to perform cleanup tasks.

Example:
// Class Component
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}

componentDidMount() {
console.log("Component mounted!");
}

componentDidUpdate() {
console.log("Component updated!");
}

componentWillUnmount() {
console.log("Component unmounting!");
}

render() {
return <div>Count: {this.state.count}</div>;
}
}

// Functional Component
function MyComponent() {
useEffect(() => {
console.log("Component mounted!");
return () => {
console.log("Component unmounting!");

Page. 9 [email protected]
};
}, []);

return <div>Count: 0</div>;


}

12. How would you perform a function just before a React component unmounts?
You can use the following methods to execute a function right before a component unmounts:
a) Class Components (componentWillUnmount):
• componentWillUnmount() is a lifecycle method in class components that is called just before the component is unmounted from
the DOM.

• Example:

class MyComponent extends React.Component {


componentWillUnmount() {
console.log("Component unmounting!");
// Perform cleanup tasks here
}

render() {
return <div>My Component</div>;
}
}

b) Functional Components (useEffect with Cleanup Function):


• In functional components, you can use the useEffect hook with a cleanup function. The cleanup function is executed when the
component is unmounted.

• Example:
function MyComponent() {
useEffect(() => {
console.log("Component mounted!");
// Perform side effects here

// Cleanup function
return () => {
console.log("Component unmounting!");
// Perform cleanup tasks here
};
}, []);

return <div>My Component</div>;


}

13. How do you implement React lifecycle methods in functional components?


Functional components use the useEffect hook to simulate lifecycle methods. By specifying a dependency array, you can control when
the effect is executed.
Simulating Lifecycle Methods with useEffect:
• componentDidMount: The effect will run once after the component is mounted to the DOM.

useEffect(() => {
console.log("Component mounted!");
// Perform side effects here
}, []);

• componentDidUpdate: The effect will run after every render, except for the initial render.

useEffect(() => {
console.log("Component updated!");
// Perform side effects here
}, [prop1, prop2]); // Run whenever prop1 or prop2 changes

• componentWillUnmount: The cleanup function inside the useEffect hook will be executed when the component is unmounted.

useEffect(() => {
console.log("Component mounted!");
// Perform side effects here

return () => {
console.log("Component unmounting!");
// Perform cleanup tasks here

Page. 10 [email protected]
};
}, []);

Example:
function MyComponent() {
useEffect(() => {
console.log("Component mounted!");
// Perform side effects here (e.g., fetch data)

// Cleanup function
return () => {
console.log("Component unmounting!");
// Perform cleanup tasks here (e.g., cancel subscriptions)
};
}, []);

useEffect(() => {
console.log("Component updated!");
// Perform side effects here (e.g., update data based on props)
}, [props.someProp]);

return <div>My Component</div>;


}

14. What are the benefits of reconciliation in React?


Reconciliation is a key optimization that makes React fast and efficient. Here are its main benefits:
• Improved Performance: Reconciliation minimizes unnecessary DOM manipulations, leading to faster rendering and a smoother
user experience. This is especially important for large and complex applications.

• Efficient Updates: By only updating the necessary parts of the DOM, React avoids unnecessary work that would slow down the
rendering process.

• Virtual DOM: The use of the virtual DOM allows React to perform diffing algorithms efficiently and determine the smallest set of
changes to make to the actual DOM.

• Better User Experience: Faster rendering means smoother transitions, less lag, and a more responsive user interface.

15. How do you identify if a website is client-side or server-side rendered?


Here’s how you can tell if a website is primarily client-side or server-side rendered:
a) Inspect the HTML Source:
• Client-Side Rendering: The HTML source code will likely be minimal or even empty initially. Most of the content will be loaded
and dynamically populated by JavaScript after the page loads.
• Server-Side Rendering: The HTML source will contain the majority of the content, including text, images, and layout elements,
right from the start.
b) Network Tab in Developer Tools:
• Client-Side Rendering: The Network tab in your browser’s developer tools will show several JavaScript files being loaded and
numerous AJAX requests happening after the initial page load. This indicates that the website is loading and rendering content
dynamically via JavaScript.
• Server-Side Rendering: The Network tab might show fewer JavaScript files and minimal AJAX requests because the server
already sent most of the content.
c) Page Load Speed and User Experience:
• Client-Side Rendering: The initial page load might be slower as the browser needs to download and execute JavaScript to
render the content. However, after the initial load, the page can be more interactive and responsive.
• Server-Side Rendering: The initial page load will be faster because the server has already sent the rendered HTML. However,
the user experience might feel less responsive as some interactions might require waiting for JavaScript to load.

16. How does Next.js work behind the scenes, and how does it create web pages, especially static ones?
Next.js uses a combination of server-side rendering (SSR), static site generation (SSG), and intelligent build processes to create high-
performance websites.
a) Building Process:
1. File Analysis: Next.js analyzes the files in your pages directory to understand the routes and components in your application.
2. Data Fetching: For SSG pages, Next.js executes the getStaticProps function during the build process to fetch data and pre-
render the pages as static HTML files.
3. HTML Generation: Next.js generates pre-built HTML files for each page, along with JavaScript bundles for dynamic components.

Page. 11 [email protected]
b) Serving Pages:
• Static Pages: When a user requests a static page (SSG), Next.js directly serves the pre-built HTML file from the build output. This
results in lightning-fast initial page loads.

• Dynamic Pages: For dynamic pages (SSR), Next.js runs the getServerSideProps function on the server when the user requests
the page. It fetches data, renders the page on the server, and sends the rendered HTML to the browser. This ensures that the
content is always up-to-date.

c) Data Fetching:
• getStaticProps: This function is used for statically generated pages (SSG). It fetches data during the build process and provides
data to the components.
• getServerSideProps: This function is used for server-side rendered pages (SSR). It fetches data on every request and provides
data to the components.
Example:
// pages/blog/[slug].js
import { getBlogPost } from "../lib/api";

export async function getStaticProps(context) {


const { slug } = context.params;
const blogPost = await getBlogPost(slug);
return {
props: { blogPost },
};
}

export default function BlogPost({ blogPost }) {


return (
<div>
<h1>{blogPost.title}</h1>
<p>{blogPost.content}</p>
</div>
);
}

• Explanation:
– This example demonstrates SSG for a blog post page.
– The getStaticProps function fetches the blog post data during the build process.
– The blogPost data is then passed to the BlogPost component as props.
– Next.js pre-renders the HTML for each blog post, resulting in fast initial loads.
In Summary: Next.js’s approach to building web pages combines SSG, SSR, and a streamlined build process to deliver high-performance,
SEO-friendly websites.

Page. 12 [email protected]

You might also like