0% found this document useful (0 votes)
3 views63 pages

ReactJS Interview Questions

The document provides an overview of React JS, explaining it as a JavaScript library for building frontend web applications, particularly Single Page Applications (SPAs). It covers key concepts such as libraries, frameworks, Virtual DOM, components, state management, and the use of hooks like useState. Additionally, it discusses tools like Vite and NPM, as well as best practices for structuring React applications and using props for data passing between components.

Uploaded by

Voku
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)
3 views63 pages

ReactJS Interview Questions

The document provides an overview of React JS, explaining it as a JavaScript library for building frontend web applications, particularly Single Page Applications (SPAs). It covers key concepts such as libraries, frameworks, Virtual DOM, components, state management, and the use of hooks like useState. Additionally, it discusses tools like Vite and NPM, as well as best practices for structuring React applications and using props for data passing between components.

Uploaded by

Voku
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

Que What is React JS?

Ans ●​ React is a JavaScript Library


●​ Used to make frontend web apps
●​ With React we can make SPA (Single Page Applications)

Que What is a Library?

Ans A library is a collection of pre-written code (functions, classes, utilities, modules, etc.) that
developers can use to perform common tasks without writing everything from scratch.

✅ Key Characteristics of a Library:


●​ Reusable Code: Libraries offer pre-built solutions for common programming challenges,
such as handling dates, rendering user interfaces, or performing mathematical calculations.
●​ Focused Scope: Typically, libraries are designed to address specific problems rather than
offering a comprehensive suite of functionalities.
●​ Developer Control: The developer maintains full control when using a library. You decide
when and how to import and call its functions.
●​ Examples:
○​ React: A library for rendering user interfaces.
○​ Lodash: Provides utility functions for working with arrays, objects, and strings.
○​ jQuery: A library specifically for manipulating the Document Object Model (DOM).

Que What is a Framework?

Ans A framework is a predefined structure or skeleton for building applications.


It not only provides reusable code (like a library) but also defines rules, flow, and architecture that
your code must follow. It is more code flow restricted than library.

Que What is an SPA (Single Page Application)?

Ans An SPA is a web app that loads only one HTML page (usually [Link]) and updates the content
dynamically using JavaScript instead of reloading the entire page for whole navigation.
Que Why use ReactJS instead of other libraries like (AngularJS, VueJS)?

Ans Because
●​ It uses Virtual DOM
●​ Easy to learn that other technologies
●​ High demand and lots of jobs in Market
●​ Large Community
●​ After Learning ReactJS we can easily learn React Native for mobile development

Que What is Virtual DOM in ReactJS?

Ans The Virtual DOM (VDOM) is a lightweight, in-memory representation of the actual DOM
(Document Object Model).

How it Works:
●​ React creates a virtual copy of the UI.
●​ When the state of a component changes, React first updates this Virtual DOM.
●​ It then compares the updated Virtual DOM with the previous Virtual DOM to identify the
differences (diffing algorithm).
●​ Only the parts of the actual DOM that have changed are then updated, rather than
re-rendering the entire UI. This process is called Reconciliation.

Benefits:
●​ Performance: Minimizes direct manipulation of the actual DOM, which is slow.
●​ Efficiency: Batches multiple updates to the real DOM, reducing rendering time.

Que Does ReactJS actually use a VDOM?

Ans Yes, React does use a Virtual DOM, but…


👉 It’s not a literal “copy of the browser’s DOM.” Instead, it’s a representation of the UI as
JavaScript objects (a tree structure).

●​ When you write JSX, React compiles it into React elements (plain JS objects).
●​ These objects describe what the UI should look like.​
●​ React builds a tree of these objects = Virtual DOM tree.

React's rendering process involves two main phases:

1.​ Render Phase:


○​ React constructs a new Virtual DOM tree from your JSX.
○​ It then compares (diffs) this new tree with the previous one.
○​ The system determines the most efficient set of changes required.
2.​ Commit Phase:
○​ React applies only these identified changes to the actual DOM.

Fiber Architecture (React 16+):

Beyond a simple Virtual DOM, modern React uses Fiber. This is an advanced re-implementation of
the reconciliation algorithm, allowing React to:

●​ Break rendering work into smaller chunks.


●​ Pause, prioritize, and resume work as needed.

This architecture significantly improves performance for animations and complex applications.

Que React set up with Vite

Ans Think of Vite like a super-fast kitchen for cooking your web app.

Vite is a super-fast tool that helps developers run and build modern web apps more efficiently
than older tools like Webpack

React Setup With Vite:

●​ Install Node and NPM


●​ Install Vite
●​ Make a react App

Que What is NPM?


Ans NPM (Node Package Manager) is the default package manager for [Link].

👉 It helps developers install, share, and manage packages (reusable pieces of code) for their
JavaScript projects.

Key Functions of NPM:

●​ Package Installation: Allows you to install third-party libraries and tools into your project.
●​ Dependency Management: Tracks all the packages your project needs in a [Link]
file.
●​ Script Runner: Can execute scripts defined in your [Link] (e.g., npm start, npm
test).
●​ Publishing Packages: Enables developers to publish their own packages for others to use.

Think of it like an app store for JavaScript code!

Que Why should we use Vite?

Ans ●​ It is a fast development server and build tool


●​ Efficient production build
●​ Simple configuration
●​ Typescript Support
●​ Supports Features like CSS-Precprocessors

Que What are CSS-Preprocessors?

Ans A CSS Preprocessor is a tool that lets you write CSS in a more powerful, advanced language
(with features normal CSS doesn’t have), and then it compiles (transpiles) it into plain CSS that
browsers understand.

Que What is a bundler?

Ans A bundler is a tool that takes all your project’s files (JavaScript, CSS, images, etc.) and combines
(bundles) them into fewer files that the browser can understand and load efficiently.
Vite is a frontend build tool that uses a dev server + a bundler under the hood.
Que Why do we need bundlers?

Ans
Modern web apps are built with:

●​ Many small JavaScript files (modules)


●​ CSS files, images, fonts, etc.
●​ New features (ES6+, JSX, TypeScript) that browsers don’t always understand directly

👉 Browsers like simple, optimized files (few JS + CSS files).​


A bundler acts as the middleman:

1.​ Take all your messy, modular code.


2.​ Converts/transpiles it (if needed).
3.​ Outputs optimized bundles ready for the browser.

Que Which file is executed First in ReactJS?

Ans First the [Link] is executed

Iske ander ek [Link] hai which looks like this initially looks like the file below image
Ye kya kar rha hai ki ye getElementById(‘root’) se uper wale [Link] de root class wale div ko
dhoondha aur jitna bhi app wala code hai </App> usko is div ke ander dal diya.

[Link] me jo bhi code hoga vo output me page pe show hoga

[Link] Output

Is [Link] file ko ham ek component bolenge

Que Why do we need to start a component’s Name in React With Capital Letter?
Ans Capitalizing React component names is a crucial convention for several reasons:

1.​ Distinguishes from HTML: React uses capitalization to differentiate your custom
components (e.g., MyComponent) from standard HTML tags (e.g., div). If lowercase, React
would treat it as an unknown HTML element.
2.​ JSX Transpilation: This convention is vital for how JSX is converted into
[Link]() calls. Capitalized tags become component references, while
lowercase tags become string names for HTML elements.
3.​ Readability: Uppercase starting letters make it easier to quickly identify custom components
in your codebase, improving readability and maintainability.
4.​ Avoids Conflicts: It prevents potential naming clashes with current and future lowercase
HTML elements.

In essence, capitalizing component names ensures correct React interpretation, proper JSX
handling, and enhances code clarity.

Que File and Folder Structure in React

Ans Here it is
Folders:

●​ Writing_First_React_Code: Your project's root


container.
●​ node_modules: Where all your project's downloaded
libraries live.
●​ public: Stores static assets served directly, like
[Link].
●​ src: Contains all your actual React application's source
code.
○​ assets: Holds static files (images, fonts) that
are processed by the build tool.

Files:

●​ .gitignore: Tells Git which files and folders to ignore.


●​ [Link]: Configures code quality and style
checking.
●​ [Link]: The single HTML entry point where your
React app renders.
●​ [Link]: Defines project metadata and lists all
dependencies and scripts.
●​ [Link]: Locks down exact versions of all
installed packages for consistency.
●​ [Link]: Provides essential project information and
instructions.
●​ [Link]: Configures Vite, your development server
and build tool.
●​ [Link]: The main JavaScript entry point that mounts
your React app to the DOM.
●​ [Link]: Your root React component, the top-level
container for your UI.
●​ [Link]: Styles specific to your [Link] component.
●​ [Link]: Global styles applied across your entire
application.

Que What is a Component in React?

Ans Jab ham koi badi cheej banate hai to uske chote chote parts ko component kehte hai. To usi tarah ek
react project ka ek chota sa part hota hai component.

The image shown below shows a React App with multiple compnents
Ek component ke ander further aur components bana sakte hai. For Ex: SIDENAV ke ander ek aur
component bana sakte hai

Que How to Use a React Component?

Ans Ya to tum [Link] me multiple components banao ya alag se bana ke [Link] me import karke use
Karo. Ham dusra bana ke imprt krne wala method dekhte hai pehle tum khud karna
First make a component and export it and after that,
You can use it by importing it in a file in a self-closing or non self-closing tag <component/>

Que How would you differentiate between a React component and a JavaScript Function?

Ans Uper ke images se dekho component me JSX syntax hoga aur function me keval JavaScript ka code
hoga.

Que Importing and Exporting Components

Ans Jab ek component bana ke dusre file me bhejte ho to uso bolte hai export aur jis file me use krte ho
us component ko manga ke usko bolte hai import “How to use a React component" wale question
me dekho.

Default Export:
Ek file (here UserComponents) se ek hi default export allowed hota hai baki agar aur exports karne
hai same file se to named export kar sakte ho

[Link] [Link]

Named Export:
Agar named export karte ho to curly braces laga ke import karna padta hai
[Link] [Link]

Que What is JSX In React?

Ans JSX is a syntax extension for JavaScript that lets you write HTML like markup inside an JavaScript
file. Although there are other ways to write components without JSX.
Some people call JSX as JavaScript Extension and some call it JavaScript XML but in the official
documentation nothing is mentioned.

Que How can you show HTML elements without JSX?

Ans For this we have to Use createElement and then create an element with it and then return that
element. It is a bit inconvenient to use this method rather we should use JSX
Que JSX With Curly Braces

Ans Displaying Variables and Calculations

Displaying a Variable Displaying a Calculation Using Function

Using with Object Using With Array Using With Tags

Que Using function call along with onclick event in ReactJS

Ans onClick in ReactJS Expects the definition of a function not its calling
See the examples below to understand
If u do like this for calling then the alert will This is the correct way because here we are
come before calling of the function passing the definition of an arrow function

Que Which fruitName function will be called here as shown in the image code below?

Ans Ander wala call hoga because JS (and by extension React) first looks for it in the current scope first
Que Follow Up for above question: Agar ander wala fruitName function hata de aur bahar wala rehne
de to kya bahar wala call hoga ya error aaega?

Ans Error nahi aaega bahar wala call ho jaega

Que How can you upgrade/downgrade the version of ReactJS that you are using in your project?

Ans ●​ Go to [Link] file


●​ Change the version of react and react-dom to your desired one
●​ Delete node_modules folder from your project
●​ Again reinstall node_modules using terminal

Que Explain what is state in ReactJS?

Ans To understand it consider this example given below in this image code

Is code ko dekh ke lagega ki button click karne se Apple ki jagah banana dikhega Page pe. Par aisa
hoga nahi, fruit ki value change hoke apple se banana to ho jaegi par page pe abhi bhi apple hi
dikhega. Kyoki ReactJS me UI me changes tabhi dikhte hai jab vo component rerender hota hai.

To is component ko render karne ke liye hame state variable banake usko change karna padega
because state variable me changes hone par hi component re render hoga.
Que But wait, What is a state?

Ans ●​ State is a container to store data like variables


●​ It is mutable and dynamic
●​ We have to import it to use it
●​ Whenever state changes the component re-renders and the changes are reflected on the UI

Que How can we use state?

Ans We need to use Hooks i.e import hooks to use states


Some of the commonly used hooks are

Que What are Hooks?

Ans Hooks are special features of functional components.


Hooks lets you use different features from your components such as state, lifecycle methods,etc.

Que Explain useState() Hook in ReactJS

Ans
The useState Hook is a React Hook that lets you add state to functional components.

In short:

●​ It gives your functional component a way to "remember" data that can change over time.
●​ It returns an array with two items:
1.​ The current state value.
2.​ A function to update that state value.
●​ When you call the update function, React re-renders the component with the new state.

Que Explain How properly change a variable on UI using useState


Ans

Que What is the Difference between a state and a variable?

Ans The difference is state is used when we have to reflect the changes in a variable on UI. On the
other hand, a variable is used to store some value.

Que Counter Problem

Ans

Que Toggle or hide and show in ReactJS

Ans Core JavaScript ke ander ye functionality banane ke liye ham element ka style change kr dete hai
Hide ke liye display=”none” aur show ke liye display=”block” par ReactJS me ye Ais =e nahi
implement hota hai, Yaha pe ham state ka use karte hai aur conditionaly items ko render karwate
hai. Iske steps hai as follows:
●​ Define state
●​ Update state on button click
●​ Hide and show component

Example:
The condition display?<h1>Deepak Singh</h1> is called Conditional Rendering. When you will
click on the button The Heading will disappear from UI and if you click again it will reappear
Que How to use this conditional Rendering for multiple conditions so that different elements are
rendered for different conditions.

Ans
Que What is a prop in ReactJS?

Ans Jab bhi ReactJS me hame data ek component se dusre component me pass karna hota hai tab ham
props use karte hai.

[Link] [Link]

Isko karna ka ek aur tarika hai which is shown in the image below

Similarly you can pass objects, arrays etc.

Que Give an example of passing prop using a button click


Ans
[Link] [Link]

Que What are default props?

Ans They are just like default arguments in a function. Agar props pass nhi kia gaya to default jo diye
honge vo pass ho jaega

Is example me dekho <User/> component me prop nahi pass kiya gaya par default wala use ho rha

[Link] [Link] Output


Que How to pass JSX code through props OR What is Children Props?

Ans
[Link]

[Link]

Output
To isme hua ye hai ki <Wrapper> tag jo ki [Link] me hai (isko self closing nahi rakhna hai) uske
ander kuch JSX code likha hai ap iske pass krna hai. To [Link] me prop {Children} likh ke
receive karo to pass kia hua JSX recieve ho jaega [Link] me.

Que How to get input field values in ReactJS?

Ans Steps:
●​ Make input field
●​ Define State
●​ Get input field value in State
●​ Display Value
●​ Clear Input field and value

Que What are controlled components in ReactJS?

Ans A controlled component is a form whose input field value is controlled by React’s state. Form hona
important nahi hai bas input field ki value state ke sath control honi chaiye.
Here’s how it works:
●​ Store input field value in a State
●​ Use change Handler with input field
●​ Value attribute attached with state
Basically hame Form bharne ke turant baad Input fields ki values chaiye jitne bhi input fields ho aur
aisa ham state ka use karke kar sakte hai
Que Handling Checkboxes in ReactJS through state

Ans ●​ Make Checkboxes


●​ Define state for check boxes
●​ If one/more ticked store them in array
●​ If one/more unchecked remove them from array

To isme ham kya kar rhe h ki check karne par state ki help se array me checkbox ki value dal rhe h
aur uncheck pe array se nikal rhe hai using state
Que Handle Radio and dropdown using state

Ans ●​ Make radio buttons


●​ Get radio button value in state
●​ Default selection of radio button
●​ Make dropdown
●​ Get dropdown value in state
●​ Default selection in drop down

useState(‘female’) se by default female selected hoga

Que Loop in JSX Using Map function

Ans Return statement ke ander map use krna padega uske bahar agar loop karna hai to normal for ya
while loop use kar sakte ho.

Agar simple data hai to simple array banalo agar complex hai to array of objects bana sakte ho
Is example me <tr key={[Link]}> usko uniquely identify karne ke liye diya gaya hai, so that error na
aaye

Output
Que Reusing a component in Loop

Ans ●​ Make Component


●​ Apply map for loop in JSX
●​ Render component in loop
●​ Pass data inside component in loop
●​ Add style
[Link] [Link]

Output
Que Make A digital Clock in ReactJS us clock ke ander ka time wala text should changeable. Implement
the color changing functionality using props

Ans
[Link] [Link]

Que Nested Looping in ReactJS

Ans ​ [Link] → Loops through colleges using .map()

​ [Link] → Shows each college and sends students to the next component

​ [Link] → Loops through and displays students

We had an array of objects and inside each object we had an array (nested)

Que Hooks in ReactJS

Ans In older versions of react we were using class based components before 16.8 version of react to un
class based components me ham state vagaira directly use kr sakte the. But ab functional
components use hote hai aur usme to directly state vagaira use kar nahi sakte isly states vagaira
use karne ke liye Hooks ko introduce kiya gaya.
Que Explain useEffect hook in ReactJS

Ans useEffect hook ka use ham tab kar sakte hai jab
●​ Remove side effects from inside component
●​ Remove side effects from outside component
●​ Fetch data
●​ Use as life cycle method
●​ For DOM Manipulation

Que Explain handling of state side effects using useEffect hook

Ans Suppose koi component ke ander koi function hai to vo function bar bar call hoga jab vo component
re render hoga bar bar.
Jese is example me state update hone pe ye test function bar bar call hoga kyoki ham jab bhi
counter ko update karenge poora component re render hoga aur jab re render hoga to ye
function bhi call hoga bar bar. To yahi hai side effect of state aur isiko hame handle karna hai

To isko ham handle karenge using useState hook ab ye bas ek baar call hoga
Que More about useEffect hook

Ans

To dependency array me agar state dete ho joi bhi to function tabhi call hoga jab vo state update
hoga varna agar kuch nahi dete ho dependency array me to function bas ek baar call hoga

Que Explain handling of props side effects using useEffect hook

Ans
[Link] [Link]
Isme jab bhi count prop update hoga to fir se side effect occur hoga aur handleCounter function call
hoga isliye useeffect me us function ko call kiya isse vo ek bar call hoga. Agar chahte ho har bar
props updation pe call ho to usko useEffect ke dependency array me daal ke use karo

Que What is the component life cycle in ReactJS?

Ans

Mount : Jab koi component UI pe show hona chalu hota hai


Update : Component ka update/ grow hona
Unmount : UI se component ka gayab hona

Que How to handle React life cycle methods Through ReactJS useEffect Hook?

Ans Iska matlab ye hai ki if you want ki kisi component ke mount/update/unmount hone pe kuch react
code execute ho to vo ham kar sakte hai useEffect() hook use karke
Que How many ways are there to add styling in ReactJS ?

Ans ●​ Inline style


●​ External style
●​ CSS Modules
●​ Styled Components
●​ External CSS Library/Framework
Inme se kitne bhi tarike ek sath ek project me use kar sakte ho

Que Explain Inline styling in ReactJS

Ans

Jab han React me inline styling use kar rhe hote hai to usko JavaScript objects se style karte hai aur
ek object me properties alag karne ke liye comma lagate hai semicolon nahi aur camelCase use
karte hai

Que How to do Dynamic and conditional Inline Style In ReactJS?

Ans
Suppose you want to create a user profile card
like on the left side and want to change the
background color and text color through the
given buttons dynamically, then you can
change it using state variables and and
changing the Inline CSS of the profile card
dynamically through the state variables
Que How to use External Styling in ReactJS?

Ans ●​ Make CSS file


●​ Write style in CSS file
●​ Import CSS file and use

Que How to style with CSS Modules in ReactJS?

Ans We need CSS modules to solve common problems that arise with global CSS, such as naming
conflicts, code complexity, and style isolation issues. They provide a way to scope CSS locally to a
component, ensuring that styles for one component do not unintentionally affect other parts of the
application.

We have to use .[Link] extension for creating a css module


[Link] [Link]

Here h1 with class heading in [Link] wont be styled but it will be styled in [Link]

Que What are styled components in ReactJs?

Ans Styled-components is a library that allows you to write CSS-in-JS, enabling you to create reusable
and encapsulated components with their own styles. It uses tagged template literals in JavaScript
and the power of ES6 to bridge the gap between components and styling.​
There are two ways you can write css in styled component​
Example usage and output

[Link] Output

Que Explain about UseRef Hook in ReactJS.


Ans The useRef hook in React returns a mutable ref object whose .current property is initialized to
the passed argument. The primary purpose of useRef is to persist a value across re-renders
without causing a component to re-render when the value changes. It's commonly used to access
and manage a direct reference to a DOM element or to store any mutable value.

Example:

[Link] Output

Here we can see that we can control the input element


Before Click on button
With the useRef hook.

After click on button

Note: UseRef is for mutable, not reactive values. A useRef object is just a plain javaScript object
with a .current property. React does not monitor this object for changes. When you update it, you
are doing it so imperatively without invoking React’s rendering engine.

Que What is an uncontrolled component in ReactJS?

Ans We know that a controlled component is a form (generally not always) whose input field value is
controlled by React’s state. Similarly agar values ko directly DOM se uthae not through state then
that will be called an uncontrolled component.
Here is an example of An uncontrolled component form using querySelector​

Here is an uncontrolled form use useRef()

Que How to pass function in component as a prop?


Ans ●​ Make parent and child component
●​ Call function from parent to child component

[Link] [Link]

Que Explain forwardRef in ReactJS

Ans Jese useRef() se kisi element ka reference lete the na vese hi agar reference alag component me ho
aur input filed (jiska reference hai) vo alag component me tab forward Ref Use karte hai
[Link] [Link]
Que Explain useFormStatus hook in ReactJS

Ans
The useFormStatus hook gives you the submission status of a parent <form> from within a
component. It returns an object with a single property, pending, which is a boolean value.

●​ pending is true when the form is in the process of submitting.


●​ pending is false when the form is not submitting.

This hook is designed to simplify how you manage loading states for submit buttons and other UI
elements inside a form. It eliminates the need to pass state down from the form component to its
children, a pattern known as "prop drilling."

Example:
Que Explain useTransition hook in ReactJS

Ans Agar kisi button ko disable karna ho for some time then we can use this isko ham bina
useTransition hook se bhi implement kar sakte hai

Lekin agar useTransition use kare to hame pending ko true false set nahi krna padega vo apne aap
ho jaega
Que What is the difference in useFormStatus hook and useTransition hook?

Ans useFormStatus hook ke liye fom ka hona must hai aur form ke submit button pe use karte hai but
useTransition ke liye form nahi chiaye kisi bhi button pe laga sakte hai isko

Que What is a pure component in ReactJS?

Ans Pure component ek aisa component hai jo apne bahar ke cheejo ko change nahi karta hai
For example agar koi variable component ke bahar hai to usko use krna chahte ho component me
ander to directly us variable ko mat use kro usko component me props ke through use kro

Is example me dekho count variable jo ki component ke bahar hai usko directly na use krke props
ke though use kar rhe hai

Example:
Que What is the derived state in ReactJS?

Ans ●​ State that is calculated or derived from other state values or props within your component
●​ Derived state can be a variable
●​ No need to use extra state we can use constants or variables

In this example the variables total, last and unique are derived states

Que What is meant by the Lifting Up state? OR Sharing state between components?

Ans Lifting state up is a technique in React where you move the state from a child component to its
closest common parent component. This allows multiple sibling components to share data.

The Problem it Solves


In React, data flows in a single direction: from parent to child (top-down). If two sibling
components need to communicate or share the same state, they can't do so directly.
Example:

[Link] [Link] [Link]

Is example me [Link] me state na paas krke parent me kardi (lift up state) aur parent se fir
required cheeje props ke through children me pass kar di

Que How to update objects which are being used as state variables?

Ans App directly update nahi kr sakte objects ko jese ab tak state variables ko karte aa rhe hai aur aisa
islye hai because

"The reason we cannot directly mutate an object or array in React state, unlike a simple variable, is
because of React's mechanism for detecting changes and triggering re-renders, known as the
reconciliation process.
This mechanism relies on a concept called shallow comparison of the state.

1. The Role of References

In JavaScript, objects and arrays are non-primitive data types, meaning they are stored by reference
(a memory address), not by value.

●​ Primitives (e.g., number, string): When you update a number from 5 to 6, React compares
the two values directly (5 !== 6). The change is obvious.
●​ Objects/Arrays: When you call the state setter function (like setData), React compares the
new object's memory address with the old object's memory address.

2. The Failure of Direct Mutation

If we mutate the object directly—for instance, [Link] = 'New Name'—and then pass that
same object back to the setter function (setData(data)):

1.​ The content of the object changes (name is updated).


2.​ However, the object's memory address remains the same.
3.​ React performs its shallow comparison and sees that oldReference ===
newReference.
4.​ It incorrectly concludes that nothing has changed and skips the re-render, leading to a
stale UI that doesn't reflect the updated data.

3. The Solution: Immutability

To correctly inform React that a change has occurred, we must use techniques like the spread
operator (...) to create a brand-new object or array. This forces a change in the memory address,
ensuring React sees oldReference !== newReference and triggers the necessary re-render.

For example, to update a nested object, we must spread at every level of the object structure to
ensure every parent object gets a new reference on its way up to the root state.

Here is an example how to do it


Que How to update Array in State?

Ans
Que Explain useActionState hook in ReactJS

Ans

Que Explain useId hook in ReactJS

Ans It is used for generating unique IDs

Que What is Fragment in ReactJS?

Ans
A Fragment in React is a feature that lets you group multiple children elements without adding an
extra node to the DOM.

In React, every component's render or return method must return a single root element. If you
have multiple elements, you traditionally had to wrap them in a redundant parent <div>.
Fragments solve this issue by serving as a logical wrapper that does not produce any HTML
output.

1. The Problem Fragments Solve: Single Root Element

React components must return a single JSX element. This constraint often forced developers to
unnecessarily nest their elements inside a surrounding <div>:

// Problem: Adding an unnecessary <div> to the DOM


function Columns() {
return (
<div>
<td>Hello</td>
<td>World</td>
</div>
);
}
This extra div is problematic because it can break flexible layouts, like CSS Flexbox or Grid, and
introduce extra complexity into the DOM structure.

2. The Solution: Two Syntaxes

Fragments allow you to group the elements without introducing the extra div. There are two ways
to use them:

A. Full Syntax (Allows Key Prop)

You can explicitly import and use [Link]. This syntax is required if you need to pass the
key prop (e.g., when rendering a list of fragments).

import React from 'react';

function Columns() {
return (
<[Link]> {/* This element is invisible in the final DOM */}
<td>Hello</td>
<td>World</td>
</[Link]>
);
}

B. Short Syntax (Most Common)

For simple grouping where no props are needed, you can use the empty tag syntax, which is the
most common way developers use fragments:

function Columns() {
return (
<> {/* This is the shorthand for <[Link]> */}
<td>Hello</td>
<td>World</td>
</>
);
}
Que What are the rules for creating custom hooks in React JS?

Ans ●​ Hook name should start with ‘use’ prefix


●​ Use Hook at top level

●​ Do not call hooks inside loops or conditions


●​ Do not call hooks after a return statement
●​ Do not call hooks in class components use in only functional components
●​ Do not call hooks in try/catch/finally blocks

[Link] Custom Hook ([Link])

Que What is Context API in ReactJS and why to use it?

Ans Understand through this example


Suppose college component se kuch data subject component me bhejna hai hame to abhi tak
hamne is kese kiya tha ki props ke through college component se class component me data pass
kro fir usko class component se student component me pass karo aur fir student component se
subject component me
Par ye reliable tarika nahi hai bcz agar nesting aur deep hoti to problem hoti and app slow ho
jaega

To context API use karke ham college component se directly data subject component me bhej sakte
hai without prop drilling(jo uper data pass-data pass kr rhe the vahi hai prop drilling)

Que Explain key components of context API

Ans createContext:
To initiate context API
Provider:
Used for updating or providing data (uper wale ex me ye college component pe lagega)
useContext:
Get data from context API (uper wale ex me student component pe lagega ya jaha bhi chaiye vaha)

createContext ek alag file rhegi jo connected rhegi jaha pe provide aur usecontext hai vaha se

Que What is react-router?


Ans
React Router is a standard library for routing in React applications. It enables the development of
single-page applications (SPAs) by managing navigation and allowing you to synchronize the UI
with the URL.

Que Explain react-router in Detail

Ans What is BrowserRouter?


This component enables client-side routing using the browser’s history API.
Server-side Routing: jab bhi kisi naye page pe jane pe routes change ho aur page refresh ho
Client-side Routing: jab bhi kisi naye page pe jane pe routes change ho aur page refresh na ho

BrowserRouter ka wrapper banan hota hai jaha pe bhi react-router use krna chahte ho to behtar ye
hoga ki isko [Link] file me rakho top level pe

Routes
Jitne bhi pages banenge vo iske ander aaenge i.e responsible for rendering appropriate component
Based on the current URL

Link
A link to navigate from one page to another page.

[Link] [Link]
These Home, About and Login are separate jsx pages

Que How to make a 404 Page?

Ans
[Link] [Link]

Agar koi route match nahi hua URL me to last wala chal jaega

Que What is nested Navigation?

Ans Navigation ke ander navigation


Suppose uper wale example me College ke ander nested routes banane hai

[Link] [Link]
Que What is the difference between <Link> and <NavLink>

Ans Link

Ye kya hai? Ye HTML ke <a> tag ka react-router version hai

Kya krta hai? Ye ek component se dusre component pe navigate karta hai bina reload kiye

styling? Sirf static styling leta hai, yani jo styling doge vohi hamesha applied rhega

Example <Link to="/products"> View all products </Link>

NavLink

Ye kya hai? Ye <Link> hi hai par isme active state recognize karne ka feature hai

Kya krta hai? Jab iska to path (destination) current URL se match karta hai (matlab aap abhi
uss page par hain), toh yeh automatically ek active class add kar deta hai.

styling? Yeh dynamic styling ke liye best hai. Yeh aapko ek function deta hai jahaan aap
check kar sakte hain ki isActive prop (property) true hai ya false.

Example <NavLink to="/home" className={({ isActive }) => isActive ? 'highlighted-link' :


'normal-link'} > Home </NavLink>

Que What are Layout Routes?

Ans Ye wala jo Navigation Bar banaye the na, agar chahte ho ki ye bar Home, Login, About pe dikhe par
College wale pe na Dikhe to aise case me ham Layout Route use karte hai
To uske liye ye changes karo

[Link]
[Link]

[Link]
Que What is index route

Ans Ye tab use karte hai jab kisi route ko by default show krna hota hai.
For example, is page me manlo ham chahte hai student wala route show ho by default r=then we
can set it index route

<Route index element={<Student />} />

Que What is Route Prefix?

Ans Maanlo tumhare website me ek user section hai

Agar route prefix use kiya To path aise likha jata hai Full URL kya banega

/user (As Prefix) /profile /user/profile

Agar uper Navbar wale example me suppose login pe lagana ho prefix the changes will be

In [Link]
<li><Link className="link" to="/in/user/login">Login</Link></li>

In [Link]
Que What are Dynamic Routes?

Ans

Jo ye dynamic url change wala item h isko useParams se access kar sakte hai

Que Explain React Router optional Segment

Ans Segment kya hai?


Suppose ek URL hai deepak/in/user/login to isme ‘in; ek segment hai ‘user’ ek segment hai ‘login’ ek
segment hai

Optional Segment kya hai?


To maanlo hame …/user/list pe bhi chalana ho aur …/user pe bhi chalana ho to yaha pe ‘list’ jo hai vo
optional sengment ho jaega

For this just put question mark in the segment


<Route path='/users/list?' element={<UserList/>}/>

Que What is an API?

Ans API woh zariya hai jo ek software ko dusre software se data/service lene aur dene mein help karta hai
Que What are API methods?

Ans
Method Desired Action (Request) One-Liner Description

GET Read/Retrieve Server se data maangna (data


lene ke liye).

POST Create/Submit Server par naya data bhejna


ya create karna.

PUT Update/Replace Server par maujood poore


data ko badalna (replace
karna).

PATCH Update/Modify Server par maujood data ke


sirf kuch hisson ko badalna
(modify karna).

DELETE Delete/Remove Server se data hamesha ke


liye hataana.

Que How can u set up a JSON server?

Ans Use json-server [[Link]

Que Set loading while calling data from API

Ans Use a state to check to check whether all the data from the API has come or not
Que Integrate POST method API

Ans

Que Integrate DELETE method API

Ans

Que Update user details using PUT method

Ans
Que Kisi form ke input values me by default data kise fill kare?

Ans useParams se values nikal ke state variable me store karlo aur input tag ki value vo state variable
set krdo

Que How to use the useActionState hook in ReactJS for Validation of input fields and why should you
use it when you can apply validation manually with hardcode?

Ans Because it is efficient.

Que Explain useActionState hook

Ans It return 3 things


Data
Isme form ka data aaenga

Action
Isko fetch krna pasta hai form ke action attribute ke sath

Pending
For validation and error handling

It takes a function as a parameter

Que Explain useReducer hook in ReactJS

Ans It is an alternative to useState hook. Par isko har jagah nahi use krna chaiye kyoki iska code thoda
bada aur heavy hota hai

Kab use karna chaiye isko


Maanlo tumare pas koi form hai jisme kai saari input values hai to un input values ko handle karne
ke liye ya to tum utne states define kro ya fir ek state ke ander array bana ke utne values store kro
par itne tamjham se bachne ke liye tum use kr sakte ho useReducer hook.
Que What is Lazy Loading in ReactJS?

Ans
Lazy loading in React is a technique used to defer the loading of component code until the
moment it's actually needed, rather than loading everything upfront. This is often called code
splitting.

It's primarily an optimization technique that helps reduce the initial bundle size of your application,
leading to faster initial page load times, especially important for Single-Page Applications (SPAs).

Example: Loading a User component only when button is clicked

Que What is the ‘use’ API in ReactJS?

Ans
Que

Ans

Que

Ans

Que

Ans

Que

Ans

Que

Ans

Que

Ans

Que

Ans

You might also like