0% found this document useful (0 votes)
1 views62 pages

React Js

The document provides a comprehensive list of frontend interview questions and answers, focusing on React.js, Redux, JavaScript, Tailwind CSS, and Git. It covers key concepts such as the virtual DOM, component lifecycle, hooks, and the differences between functional and class components. Additionally, it discusses practical aspects like API calls, error handling, and creating responsive designs.

Uploaded by

priyakush1002
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)
1 views62 pages

React Js

The document provides a comprehensive list of frontend interview questions and answers, focusing on React.js, Redux, JavaScript, Tailwind CSS, and Git. It covers key concepts such as the virtual DOM, component lifecycle, hooks, and the differences between functional and class components. Additionally, it discusses practical aspects like API calls, error handling, and creating responsive designs.

Uploaded by

priyakush1002
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/ 62

Frontend Interview Questions & Answers

React.js

Q: What is the virtual DOM, and how does React use it?

A: The virtual DOM is a lightweight JavaScript object representing the real DOM. React updates the

virtual DOM first, calculates the differences, and then efficiently updates only the changed parts in the

real DOM.

Q: Explain the component lifecycle in React.

A: React components go through mounting, updating, and unmounting phases. With class

components, methods like componentDidMount and componentDidUpdate are used. In functional

components, useEffect handles these.

Q: What are controlled vs uncontrolled components?

A: Controlled components use React state to manage input values, while uncontrolled components

rely on the DOM and useRefs for accessing values.

React Hooks & React Hook Form

Q: What are useState and useEffect used for?

A: useState manages local state in functional components, and useEffect performs side effects like

data fetching or event listeners.

Q: When would you use useCallback and useMemo?

A: useCallback memoizes functions to prevent unnecessary re-creation, while useMemo memoizes

the result of calculations.

Q: How does React Hook Form simplify form management?

A: It manages form state efficiently, provides validation, and reduces re-renders compared to

controlled inputs.
Redux & Context API

Q: What is the difference between Redux and Context API?

A: Redux is better for large apps with complex state logic, while Context API is ideal for passing down

simple global data.

Q: Explain the role of actions, reducers, and the store in Redux.

A: Actions describe changes, reducers handle the logic, and the store holds the global state tree.

Q: What is middleware in Redux? Give examples.

A: Middleware like redux-thunk or redux-saga intercepts actions to handle async logic before they

reach reducers.

React Router

Q: How do you define routes in React Router v6?

A: Use <BrowserRouter> and <Routes> with <Route path='/example' element={<Component />} />.

Q: What does useParams() do?

A: It retrieves dynamic parts of the URL, like ID or slug, from the route parameters.

Q: How would you handle a 404 page with React Router?

A: Add a Route with path='*' to catch undefined routes and show a NotFound component.

Axios & Vite

Q: How do you make API calls using Axios in React?

A: Use Axios inside useEffect or a function, e.g., axios.get('/api/data').then(res => ...).

Q: What are the advantages of using Vite over Create React App (CRA)?

A: Vite offers faster dev server startup, instant HMR, and smaller production builds using ESBuild and

Rollup.

Q: How do you handle API errors and loading states?

A: Use try-catch blocks and state variables like isLoading and error to manage UI feedback.
JavaScript

Q: What is the difference between == and ===?

A: == compares values after type conversion; === compares both type and value without conversion.

Q: What are closures, and where are they used?

A: A closure is a function that remembers variables from its outer scope even after the outer function

has returned.

Q: Explain hoisting in JavaScript.

A: Variables and functions are 'hoisted' to the top of their scope, but only declarations are hoisted, not

initializations.

Tailwind CSS & Responsive UI Design

Q: How do you make a component responsive in Tailwind CSS?

A: Use responsive prefixes like md:, lg:, xl: to apply styles based on screen size.

Q: What are utility-first classes? Give examples.

A: Utility classes like p-4, m-2, bg-blue-500 apply one style each and are composed together for fast

styling.

Q: How do you apply conditional styles in Tailwind with React?

A: Use className with ternary logic or libraries like clsx to toggle classes conditionally.

HTML 5 & CSS 3

Q: What are semantic HTML tags? Why are they important?

A: Tags like <header>, <main>, <section> add meaning to content, improving accessibility and SEO.

Q: How is Flexbox different from CSS Grid?

A: Flexbox is for one-dimensional layout (row or column), while Grid handles two-dimensional layout

(rows and columns).

Q: What is the purpose of media queries in CSS?


A: Media queries apply styles based on screen size, resolution, or device characteristics for

responsive design.

Git & GitHub

Q: What is the difference between git pull and git fetch?

A: git fetch downloads updates without merging, while git pull does both fetch and merge.

Q: How do you resolve merge conflicts?

A: Manually edit the conflicted file, remove conflict markers, then stage and commit the resolved

version.

Q: What is a pull request, and how do you create one?

A: A pull request is a GitHub feature to review and merge code. You create one after pushing your

branch to a remote repo.

1. What is ReactJS?

ReactJS is a JavaScript library used to build reusable components for the view layer in the MVC

architecture. It is used to build the Single Page Application (SPA) due to its component-based

architecture, efficient re-rendering with the Virtual DOM, and ability to manage dynamic content

without needing full page reloads. It is written in JSX.

Important Features of React:

 Virtual DOM: React uses a virtual DOM to efficiently update and render components, ensuring

fast performance by minimizing direct DOM manipulations.


 Component-Based Architecture: React builds UI using reusable, isolated components,

making code more modular, maintainable, and scalable.

 Hooks: React Hooks allow functional components to manage state and side effects, making

them powerful and more flexible.

 Server-Side Rendering (SSR): React can be used for server-side rendering, where HTML

content is generated on the server and sent to the client. This improves the app's performance,

especially for SEO.

 React Router: React Router enables navigation in a React application. It allows you to define

different routes for different views in a single-page application (SPA).

2. What is the latest version of the React?

The latest stable version of React is v19.1.0, released on March 28, 2025 . This version builds upon

the major updates introduced in React v19.0.0, which was officially released on December 5, 2024.

3. Explain the MVC architecture.

The Model-View-Controller (MVC) framework is an architectural/design pattern that separates an

application into three main logical components: Model, View, and Controller. Each architectural

component is built to handle specific development aspects of an application. It isolates the business,

logic, and presentation layers from each other

4. Explain the building blocks of React.

The five main building blocks of React are

 Components: These are reusable blocks of code that return HTML.

 JSX: It stands for JavaScript and XML and allows you to write HTML in React.
 Props and State: props are like function parameters and State is similar to variables.

 Context: This allows data to be passed through components as props in a hierarchy.

 Virtual DOM: It is a lightweight copy of the actual DOM which makes DOM manipulation easier.

5. Explain props and state in React with differences

Props are used to pass data from one component to another. The state is local data storage that is

local to the component only and cannot be passed to other components.

Here is the difference table of props and state In react

PROPS STATE

The Data is passed from one


The Data is passed within the component only.
component to another.

It is Immutable (cannot be modified). It is Mutable ( can be modified).

Props can be used with state and The state can be used only with the state

functional components. components/class component (Before 16.0).

Props are read-only. The state is both read and write.

6. What is virtual DOM in React?


The Virtual DOM in React is an in-memory representation of the actual DOM. It helps React efficiently

update and render the user interface by comparing the current and previous virtual DOM states using

a process called diffing.

How Virtual DOM Works

 Efficient Rendering: The Virtual DOM is an in-memory representation of the actual DOM that

React uses to optimize the process of updating and rendering UI changes.

 Diffing Algorithm: React compares the current and previous versions of the Virtual DOM using

a diffing algorithm, identifying the minimal set of changes required to update the real DOM.

 Batch Updates: Instead of updating the real DOM immediately, React batches multiple

changes to reduce unnecessary re-renders, improving performance.

 Faster Updates: Since updating the real DOM is slow, React minimizes direct DOM

manipulations by only making updates where necessary after comparing the Virtual DOM.

 Declarative UI: With the Virtual DOM, React allows developers to write code in a declarative

style, letting React handle when and how to efficiently update the UI.

7. Differentiate between Real DOM and virtual DOM?

Real DOM Virtual DOM

The actual DOM, a tree-like


A lightweight copy of the Real DOM used to optimize
structure representing the UI
updates.
elements.
Real DOM Virtual DOM

Slower as it requires direct updates Faster because it minimizes direct manipulation of the Real

to the actual DOM. DOM.

Directly manipulates the Real DOM, Updates are made to the Virtual DOM first, then changes

causing re-rendering of the entire are batched and only the necessary changes are reflected

UI. in the Real DOM.

Entire UI might need to be re- Only the necessary components are re-rendered, reducing

rendered when changes occur. unnecessary re-renders.

Less efficient due to repeated direct More efficient by minimizing direct DOM manipulation and

updates to the Real DOM. batch updates.

8. What is JSX?

JSX is basically a syntax extension of regular JavaScript and is used to create React elements. These

elements are then rendered to the React DOM. All the React components are written in JSX. To embed

any JavaScript expression in a piece of code written in JSX we will have to wrap that expression in

curly braces {}.

Example of JSX: The name written in curly braces { } signifies JSX

const name = "Learner";

const element = (
<h1>

Hello,

{name}.Welcome to GeeksforGeeks.

</h1>

);

9. What are components and their type in React?

A Component is one of the core building blocks of React. In other words, we can say that every

application you will develop in React will be made up of pieces called components. Components make

the task of building UIs much easier.

In React, we mainly have two types of components:

 Functional Components: Functional components are simply JavaScript functions. We can

create a functional component in React by writing a JavaScript function.

 Class Components: The class components are a little more complex than the functional

components. The functional components are not aware of the other components in your

program whereas the class components can work with each other. We can pass data from one

class component to another class component.

10. How do browsers read JSX?

In general, browsers are not capable of reading JSX and only can read pure JavaScript. The web

browsers read JSX with the help of a transpiler. Transpilers are used to convert JSX into JavaScript.

The transpiler used is called Babel.

11. Explain the steps to create a react application and print Hello World?
To install React, first, make sure Node is installed on your computer. After installing Node. Open the

terminal and type the following command.

npx create-react-app <<Application_Name>>

Note: The above method is now deprecated, so use the below given method for creating the React

application.

npm create vite@latest

Navigate to the folder.

cd <<Application_Name>>

This is the first code of ReactJS Hello World!

import React from "react";

import "./App.css";

function App() {

return <div className="App">Hello World !</div>;

export default App;

Output:

Type the following command to run the application

npm start
React app

12. How to create an event in React?

To create an event in React, attach an event handler like onClick, onChange, etc., to a JSX element.

Define the handler function to specify the action when the event is triggered, such as updating state

or executing logic.

function Component() {

doSomething(e);

e.preventDefault();

// Some more response to the event

return <button onEvent={doSomething}></button>;

13. Explain the creation of a List in React?

Lists are very useful when it comes to developing the UI of any website. Lists are mainly used for

displaying menus on a website. To create a list in React use the map method of array as follows.

import React from "react";

import ReactDOM from "react-dom/client"; // Import react-dom/client


const numbers = [1, 2, 3, 4, 5];

const updatedNums = numbers.map((number) => {

return <li key={number}>{number}</li>; // Add a unique "key" prop

});

const root = ReactDOM.createRoot(document.getElementById("root")); // Create the root

root.render(<ul>{updatedNums}</ul>); // Render the list into the root element

Output:

List

14. What is a key in React?

A key is a special string attribute you need to include when creating lists of elements in React. Keys

are used in React to identify which items in the list are changed, updated, or deleted. In other words,

we can say that keys are used to give an identity to the elements in the lists.

15. How to write a comment in React?


There are two ways to write comments in React.

 Multi-line comment: We can write multi-line comments in React using the asterisk format /*

*/.

/*

This is a multi-line comment.

It can span multiple lines.

*/

 Single line comment: We can write single comments in React using the double forward slash

//.

// This is a single-line comment

16. Explain the difference between React and Angular?

React Angular

React is a JavaScript library. As it indicates react js Angular is a framework. Angular updates

updates only the virtual DOM is present and the data the Real DOM and the data flow is ensured

flow is always in a single direction. in the architecture in both directions.

The architecture is complex as it follows


React is more simplified as it follows MVC ie., Model
MVVM models ie., Model View-
View Control.
ViewModel.
React Angular

It is highly scalable. It is less scalable than React JS.

It supports Uni-directional data binding which is one- It supports Bi-directional data binding

way data binding. which is two way data binding.

It has a virtual DOM. It has regular DOM.

17. Explain the use of render method in React?

React renders HTML to the web page by using a function called render(). The purpose of the function

is to display the specified HTML code inside the specified HTML element. In the render() method, we

can read props and state and return our JSX code to the root component of our app.

18. What is state in React?

The state is an instance of React Component Class that can be defined as an object of a set of

observable properties that control the behaviour of the component. In other words, the State of a

component is an object that holds some information that may change over the lifetime of the

component.

19. Explain props in React?

React allows us to pass information to a Component using something called props (which stands for

properties). Props are objects which can be used inside a component

We can access any props inside from the component’s class to which the props is passed. The props

can be accessed as shown below:


this.props.propName;

20. What is higher-order component in React?

Higher-order components or HOC is the advanced method of reusing the component functionality

logic. It simply takes the original component and returns the enhanced component. HOC are beneficial

as they are easy to code and read. Also, helps to get rid of copying the same logic in every component.

21. Explain the difference between functional and class component in React?

Functional Components Class Components

A functional component is just a plain JavaScript A class component requires you to extend from

pure function that accepts props as an React. Component and create a render

argument function

No render method used It must have the render() method returning JSX

Also known as Stateless components Also known as Stateful components

React lifecycle methods (for example, React lifecycle methods can be used inside

componentDidMount) cannot be used in class components (for example,

functional components. componentDidMount).

Constructors are not used. Constructor is used as it needs to store state.


Functional Components Class Components

Uses this.state and this.setState for state


Uses hooks like useState for managing state.
management.

22. Explain one way data binding in React?

ReactJS uses one-way data binding which can be Component to View or View to Component. It is

also known as one-way data flow, which means the data has one, and only one way to be transferred

to other parts of the application. In essence, this means child components are not able to update the

data that is coming from the parent component. It is easy to debug and less prone to errors.

23. What is Context API in React?

The Context API is a way to share data (such as theme, language preference, etc.) across

components without having to pass props down manually at every level. It provides a Provider

component to set the value and a Consumer component or useContext() hook to access it.

24. What is the role of shouldComponentUpdate() in React?

shouldComponentUpdate() is a lifecycle method that allows you to control whether a component

should re-render when it receives new props or state. If it returns false, React will skip the re-render

process for that component.

25. What is the use of dangerouslySetInnerHTML in React?

dangerouslySetInnerHTML is an attribute used to set raw HTML inside a component. It is generally

discouraged because it can expose the application to XSS (cross-site scripting) attacks, but it is

sometimes used for rendering third-party HTML content.


26. What are Pure Components in React?

A Pure Component is a type of React component that only re-renders if the props or state it receives

change. React provides React.PureComponent, which is a base class that automatically performs a

shallow comparison of props and state to determine if a re-render is necessary.

27. What is the significance of setState() in React?

setState() is a method used to update the state of a component. When the state is updated, React re-

renders the component and its child components to reflect the changes.

React Intermediate Interview Questions

Here, we cover all intermediate level react interview questions with answers, that recommeded for

freshers as well as for experienced professionals having 1 - 2 years of experience.

28. What is conditional rendering in React?

Conditional rendering in React involves selectively rendering components based on specified

conditions. By evaluating these conditions, developers can control which components are displayed,

allowing for dynamic and responsive user interfaces in React applications.

Let us look at this sample code to understand conditional rendering.

{isLoggedIn == false ? <DisplayLoggedOut /> : <DisplayLoggedIn />}

Here if the boolean isLoggedIn is false then the DisplayLoggedOut component will be rendered

otherwise DisplayLoggedIn component will be rendered.

29. What is React Router?


React Router is a standard library for routing in React. It enables the navigation among views of

various components in a React Application, allows changing the browser URL, and keeps the UI in

sync with the URL.

To install react router type the following command.

npm i react-router-dom

30. Explain the components of a react-router.

The main components of a react-router are:

1. Router(usually imported as BrowserRouter): It is the parent component that is used to store

all of the other components. Everything within this will be part of the routing functionality

2. Switch: The switch component is used to render only the first route that matches the location

rather than rendering all matching routes.

3. Route: This component checks the current URL and displays the component associated with

that exact path. All routes are placed within the switch components.

4. Link: The Link component is used to create links to different routes.

31. How is React routing different from conventional routing?

React Routing Conventional Routing

Typically used in Multi-Page Applications


Used in Single Page Applications (SPA).
(MPA).
React Routing Conventional Routing

No full page reloads. React updates only the Full page reload is triggered for every

necessary parts of the UI. navigation request.

React uses a client-side router (e.g., React Uses server-side routing where the server

Router) to handle navigation and manage different responds with new HTML for each

views within the same page. navigation.

Routes are managed by JavaScript, and the Routes correspond to different server-side

browser’s address bar reflects the application’s routes, and the server responds with new

state. HTML files.

32. Explain the lifecycle methods of components

A React Component can go through four stages of its life as follows.

 Initialization: This is the stage where the component is constructed with the given Props and

default state. This is done in the constructor of a Component Class.

 Mounting: Mounting is the stage of rendering the JSX returned by the render method itself.

 Updating: Updating is the stage when the state of a component is updated and the application

is repainted.

 Unmounting: As the name suggests Unmounting is the final step of the component lifecycle

where the component is removed from the page.

33. Explain the methods used in mounting phase of components


Mounting is the phase of the component lifecycle when the initialization of the component is completed

and the component is mounted on the DOM and rendered for the first time on the webpage. he

mounting phase consists of two such predefined functions as described below

 componentWillMount() Function: This function is invoked right before the component is

mounted on the DOM.

 componentDidMount() Function: This function is invoked right after the component is mounted

on the DOM.

34. What is this.setState function in React?

We use the setState() method to change the state object. It ensures that the component has been

updated and calls for re-rendering of the component. The state object of a component may contain

multiple attributes and React allows using setState() function to update only a subset of those

attributes as well as using multiple setState() methods to update each attribute value independently.

35. What is the use of ref in React?

Refs are a function provided by React to access the DOM element and the React element that you

might have created on your own. They are used in cases where we want to change the value of a

child component, without making use of props and all. They have wide functionality as we can use

callbacks with them.

The syntax to use ref is :

const node = this.myCallRef.current;

36. What are hooks in React?


Hooks are a new addition in React 16.8. They let developers use state and other React features

without writing a class. Hooks doesn’t violate any existing React concepts. Instead, Hooks provide a

direct API to react concepts such as props, state, context, refs and life-cycle

37. Explain the useState hook in React?

The most used hook in React is the useState() hook. Using this hook we can declare a state variable

inside a function but only one state variable can be declared using a single useState() hook. Whenever

the useState() hook is used, the value of the state variable is changed and the new variable is stored

in a new cell in the stack.

Syntax:

const [state, setState] = useState(initialState);

 state: The current state value.

 setState: A function used to update the state value.

 initialState: The initial value of the state.

38. Explain the useEffect hook in React?

The useEffect hook in React eliminates the side effect of using class based components. It is used as

an alternative to componentDidUpdate() method. The useEffect hook accepts two arguments where

second argument is optional.

useEffect(function, dependency)

The dependency decides when the component will be updated again after rendering.

39. What is React Fragments?


when we are trying to render more than one root element we have to put the entire content inside the

‘div’ tag which is not loved by many developers. So since React 16.2 version, Fragments were

introduced, and we use them instead of the extraneous ‘div’ tag. The following syntax is used to create

fragment in react.

<React.Fragment>

<h2>Child-1</h2>

<p> Child-2</p>

</React.Fragment>

40. What is a react developer tool?

React Developer Tools is a Chrome DevTools extension for the React JavaScript library. A very useful

tool, if you are working on React applications. This extension adds React debugging tools to the

Chrome Developer Tools. It helps you to inspect and edit the React component tree that builds the

page, and for each component, one can check the props, the state, hooks, etc.

41. How to use styles in ReactJS?

CSS modules are a way to locally scope the content of your CSS file. We can create a CSS module

file by naming our CSS file as App.modules.css and then it can be imported inside App.js file using

the special syntax mentioned below.

Syntax:

import styles from './App.module.css';

42. Explain styled components in React?


Styled-component Module allows us to write CSS within JavaScript in a very modular and reusable

way in React. Instead of having one global CSS file for a React project, we can use styled-component

for enhancing the developer experience. It also removes the mapping between components and styles

– using components as a low-level styling construct

The command to install styled components is

npm i styled-components

Using the below code we can custom style a button in React

import styled from 'styled-components'

const Button = styled.div`

width : 100px ;

cursor: pointer ;

text-decoration : none;

export default Button;

43. What is prop drilling and its disadvantages?

Prop drilling is basically a situation when the same data is being sent at almost every level due to

requirements in the final level. The problem with Prop Drilling is that whenever data from the Parent

component will be needed, it would have to come from each level, Regardless of the fact that it is not

needed there and simply needed in last.


44. What is conditional rendering in React?

Conditional rendering in React is used when you want to render different UI elements based on certain

conditions. For example, rendering a login button if a user is not logged in or rendering a logout button

when the user is logged in.

const isLoggedIn = true;

return (

<div>

{isLoggedIn ?<button>Logout</button> : <button>Login</button>}

</div>

);

45. What are controlled components in React?

Controlled components are React components where the form data is handled by the state within the

component. The form element's value is controlled via the React state, making the form elements

responsive to changes.

For further reading, check out our dedicated article on Intermediate ReactJS Intermediate Interview

Questions. Inside, you’ll discover over 20 questions with detailed answers.

React Interview Questions for Experienced

Here, we cover advanced react interview questions with answers for experienced professionals,

who have over 5+ years of experience.

46. What is custom hooks in React?


Custom hooks are normal JavaScript functions whose names start with “use” and they may call other

hooks. We use custom hooks to maintain the DRY concept that is Don’t Repeat Yourself. It helps us

to write a logic once and use it anywhere in the code.

47. How to optimize a React code?

We can improve our react code by following these practices:

 Using binding functions in constructors

 Eliminating the use of inline attributes as they slow the process of loading

 Avoiding extra tags by using React fragments

 Lazy loading

48. What is the difference between useref and createRef in React ?

Here is the difference table of useref and createRef in React

useRef createRef

It is a hook. It is a function.

It uses the same ref throughout the component's It creates a new ref every time component

lifecycle. re-renders.

It saves its value between re-renders in a functional


It creates a new ref for every re-render.
component.
useRef createRef

It returns a mutable ref object (i.e., can be It returns a read-only ref object (cannot

changed). be modified directly).

Used for accessing DOM elements, persisting


Used for class components, especially
values, or managing timers in functional
when referencing DOM elements.
components.

const myRef = useRef(); const myRef = React.createRef();

49. What is react-redux?

React-redux is a state management tool which makes it easier to pass these states from one

component to another irrespective of their position in the component tree and hence prevents the

complexity of the application. As the number of components in our application increases it becomes

difficult to pass state as props to multiple components. To overcome this situation we use react-redux

50. What are benefits of using react-redux?

They are several benfits of using react-redux such as:

 It provides centralized state management i.e. a single store for whole application

 It optimizes performance as it prevents re-rendering of component

 Makes the process of debugging easier

 Since it offers persistent state management therefore storing data for long times become easier
51. Explain the core components of react-redux?

There are four fundamental concepts of redux in react which decide how the data will flow through

components

 Redux Store: It is an object that holds the application state

 Action Creators: These are functions that return actions (objects).

 Actions: Actions are simple objects which conventionally have two properties- type and

payload

 Reducers: Reducers are pure functions that update the state of the application in response to

actions

52. How can we combine multiple reducers in React?

When working with Redux we sometimes require multiple reducers. In many cases, multiple actions

are needed, resulting in the requirement of multiple reducers. However, this can become problematic

when creating the Redux store. To manage the multiple reducers we have function called

combineReducers in the redux. This basically helps to combine multiple reducers into a single unit

and use them.

Syntax

import { combineReducers } from "redux";

const rootReducer = combineReducers({

books: BooksReducer,

activeBook: ActiveBook
});

53. Explain CORS in React?

In ReactJS, Cross-Origin Resource Sharing (CORS) refers to the method that allows you to make

requests to the server deployed at a different domain. As a reference, if the frontend and backend are

at two different domains, we need CORS there.

We can setup CORS evironment in frontend using two methods:

 axios

 fetch

54. What is axios and how to use it in React?

Axios, which is a popular library is mainly used to send asynchronous HTTP requests to REST

endpoints. This library is very useful to perform CRUD operations.

 This popular library is used to communicate with the backend. Axios supports the Promise API,

native to JS ES6.

 Using Axios we make API requests in our application. Once the request is made we get the

data in Return, and then we use this data in our project.

To install axios package in react use the following command.

npm i axios

55. Write a program to create a counter with increment and decrement?

We can create the counter app with increment and decrement by writing the below code in the

terminal:
import React, { useState } from "react";

const App = () => {

const [counter, setCounter] = useState(0)

const handleClick1 = () => {

setCounter(counter + 1)

const handleClick2 = () => {

setCounter(counter - 1)

return (

<div>

<div>

{counter}

</div>

<div className="buttons">
<button onClick={handleClick1}>

Increment

</button>

<button onClick={handleClick2}>

Decrement

</button>

</div>

</div>

export default App

Output:

Counter App using React

56. Explain why and how to update state of components using callback?

It is advised to use a callback-based approach to update the state using setState because it solves

lots of bugs upfront that may occur in the future.We can use the following syntax to update state using

callback
this.setState(st => {

return(

st.stateName1 = state1UpdatedValue,

st.stateName2 = state2UpdatedValue

})

57. What is React-Material UI?

React Material UI is an open-source React component library, offering prebuilt components for

creating React applications. Developed by Google in 2014, it's compatible with JavaScript frameworks

like Angular.js and Vue.js. Renowned for its quality designs and easy customization, it's favored by

developers for rapid development.

58. What is flux architecture in redux?

Flux architecture in Redux is a design pattern used for managing application state in a unidirectional

data flow. In this architecture, actions are dispatched to modify the store, which holds the entire

application state. The store sends the updated state to the view (UI), and the cycle repeats when new

actions are triggered. Redux follows this structure to ensure a predictable and maintainable state

management system for large applications.

59. What are custom hooks in React?

Custom hooks are user-defined functions that use built-in hooks like useState, useEffect, etc., to reuse

stateful logic across components. They allow you to extract and share common logic.

60. How can you optimize React performance?


Optimizing React performance can be achieved using:

 React.memo() for preventing unnecessary re-renders.

 Lazy loading components with React.lazy() and Suspense.

 Using useMemo() and useCallback() hooks to memoize values and functions.

 Avoiding unnecessary state updates.

61. What is the Strict Mode in React?

Strict Mode in React is a tool that helps developers find and fix problems in their app while developing.

It only works in development and doesn’t affect the app when it’s running in production. When enabled,

it checks for potential issues, such as old features that should no longer be used, and gives warnings

to help avoid bugs.

We can enable the strict mode by by wrapping your application or specific components inside

the <React.StrictMode>.

import React from "react";

import ReactDOM from "react-dom";

const App = () => {

return (

<div>

<h1>Hello, World!</h1>
</div>

);

};

ReactDOM.render(

<React.StrictMode>

<App />

</React.StrictMode>,

document.getElementById("root")

);

62. What is Redux and how does it work with React?

Redux is a state management library that helps manage the application state globally. It uses actions,

reducers, and a central store to control state. React-Redux is used to connect Redux state to React

components.

63. How does React handle concurrency?

React's Concurrent Mode is a set of features that help React apps stay responsive and gracefully

adjust to the user’s device capabilities and network speed. It allows React to interrupt rendering and

prioritize high-priority tasks.

64. How does React handle server-side rendering (SSR)?


Server-side rendering (SSR) is the process of rendering a React application on the server and sending

the fully rendered HTML to the client. This improves the initial page load performance and SEO.

65. What are forms in React?

In React, forms are a way to capture user input, such as text fields, checkboxes, radio buttons, and

buttons. React provides controlled and uncontrolled components for handling form elements, allowing

developers to manage user input and form state in an efficient and structured way.

66. How to create forms in React?

Creating forms in React involves handling user input and managing the form's state. In React, form

elements like <input>, <textarea>, and <select> are controlled components, meaning their values are

controlled by the React state.

 Create the State for the Form: Use the useState hook to manage form input values.

 Set the Value of Form Elements: Bind the form elements’ value attribute to the corresponding

state variable to make the inputs controlled.

 Handle User Input: Use an onChange event handler to update the state whenever the user

types in the form fields.

 Submit the Form: Handle the form submission with an onSubmit event, and prevent the

default behavior to stop the page from refreshing.

import React, { useState } from 'react';

function MyForm() {

// State to store input values


const [name, setName] = useState('');

const [email, setEmail] = useState('');

const [message, setMessage] = useState('');

// Handle input change for each field

const handleNameChange = (e) => setName(e.target.value);

const handleEmailChange = (e) => setEmail(e.target.value);

const handleMessageChange = (e) => setMessage(e.target.value);

// Handle form submission

const handleSubmit = (e) => {

e.preventDefault(); // Prevent default form submission behavior

console.log('Form submitted:', { name, email, message });

};

return (

<form onSubmit={handleSubmit}>

<div>
<label>Name:</label>

<input type="text" value={name} onChange={handleNameChange} />

</div>

<div>

<label>Email:</label>

<input type="email" value={email} onChange={handleEmailChange} />

</div>

<div>

<label>Message:</label>

<textarea value={message} onChange={handleMessageChange} />

</div>

<button type="submit">Submit</button>

</form>

);

export default MyForm;

Output:
React Form

67. What is Lazy Loading in React?

Lazy Loading in React is a technique used to load components only when they are needed, instead

of loading everything at once when the app starts. This helps improve the performance of the app by

reducing the initial loading time.

In React, React.lazy() is used to implement lazy loading for components, which allows you to split your

code into smaller bundles and load them only when required.

68. How is React different from React Native?

React React Native

A JavaScript library for building user A framework for building mobile applications using

interfaces, primarily for web applications. JavaScript and React.

Focuses on developing native mobile applications


Focuses on developing web applications.
for iOS and Android.
React React Native

Renders native mobile components using native


Renders HTML using the Virtual DOM.
APIs (e.g., View, Text, Image).

Uses web technologies like HTML, CSS, Uses native mobile components and styles for

and JavaScript. building mobile UIs.

Runs on mobile devices and communicates with


Runs in the browser on a web server.
native code.

Can be deployed on browsers like Chrome, Can be deployed as native apps on iOS and Android

Firefox, etc. platforms.

69. What is Memoization in React?

Memoization in React is an optimization technique used to improve the performance of a component

by preventing unnecessary re-renders. It involves caching the results of expensive function calls and

reusing the cached result when the inputs to the function haven't changed. This is particularly useful

when a component’s rendering process is slow, and you want to avoid recalculating or re-rendering

unnecessarily.

How Memoization Works in React:

React provides two key APIs for memoization:

1. React.memo(): This is a higher-order component (HOC) used to prevent re-renders of

functional components if their props have not changed.


2. useMemo(): A hook that memorizes the result of a computation and only recomputes it when

its dependencies change.

70. What is Reoncillation in React?

Reconciliation in React is the process of updating the DOM when a component's state or props

change. React uses the Virtual DOM to efficiently determine what parts of the actual DOM need to

be updated. Here's a simplified overview:

 Triggering Reconciliation: React triggers reconciliation when state or props change (e.g.,

through setState() or useState()).

 Virtual DOM Diffing: React compares the old Virtual DOM with the new one to identify

changes.

 Efficient Updates: React calculates the minimal set of changes and applies them to the real

DOM.

 Fiber Algorithm: React's Fiber algorithm allows the reconciliation process to be interrupted

and prioritized, improving performance for complex tasks.

. What is conditional rendering in React?

Conditional rendering in React involves selectively rendering components based on specified

conditions. By evaluating these conditions, developers can control which components are displayed,

allowing for dynamic and responsive user interfaces in React applications.

Let us look at this sample code to understand conditional rendering.


{isLoggedIn == false ? <DisplayLoggedOut /> : <DisplayLoggedIn />}

Here if the boolean isLoggedIn is false then the DisplayLoggedOut component will be rendered

otherwise DisplayLoggedIn component will be rendered.

29. What is React Router?

React Router is a standard library for routing in React. It enables the navigation among views of

various components in a React Application, allows changing the browser URL, and keeps the UI in

sync with the URL.

To install react router type the following command.

npm i react-router-dom

30. Explain the components of a react-router.

The main components of a react-router are:

1. Router(usually imported as BrowserRouter): It is the parent component that is used to store

all of the other components. Everything within this will be part of the routing functionality

2. Switch: The switch component is used to render only the first route that matches the location

rather than rendering all matching routes.

3. Route: This component checks the current URL and displays the component associated with

that exact path. All routes are placed within the switch components.

4. Link: The Link component is used to create links to different routes.

31. How is React routing different from conventional routing?


React Routing Conventional Routing

Typically used in Multi-Page Applications


Used in Single Page Applications (SPA).
(MPA).

No full page reloads. React updates only the Full page reload is triggered for every

necessary parts of the UI. navigation request.

React uses a client-side router (e.g., React Uses server-side routing where the

Router) to handle navigation and manage different server responds with new HTML for each

views within the same page. navigation.

Routes are managed by JavaScript, and the Routes correspond to different server-side

browser’s address bar reflects the application’s routes, and the server responds with new

state. HTML files.

32. Explain the lifecycle methods of components

A React Component can go through four stages of its life as follows.

 Initialization: This is the stage where the component is constructed with the given Props and

default state. This is done in the constructor of a Component Class.

 Mounting: Mounting is the stage of rendering the JSX returned by the render method itself.

 Updating: Updating is the stage when the state of a component is updated and the application

is repainted.
 Unmounting: As the name suggests Unmounting is the final step of the component lifecycle

where the component is removed from the page.

33. Explain the methods used in mounting phase of components

Mounting is the phase of the component lifecycle when the initialization of the component is completed

and the component is mounted on the DOM and rendered for the first time on the webpage. he

mounting phase consists of two such predefined functions as described below

 componentWillMount() Function: This function is invoked right before the component is

mounted on the DOM.

 componentDidMount() Function: This function is invoked right after the component is mounted

on the DOM.

34. What is this.setState function in React?

We use the setState() method to change the state object. It ensures that the component has been

updated and calls for re-rendering of the component. The state object of a component may contain

multiple attributes and React allows using setState() function to update only a subset of those

attributes as well as using multiple setState() methods to update each attribute value independently.

35. What is the use of ref in React?

Refs are a function provided by React to access the DOM element and the React element that you

might have created on your own. They are used in cases where we want to change the value of a

child component, without making use of props and all. They have wide functionality as we can use

callbacks with them.

The syntax to use ref is :

const node = this.myCallRef.current;


36. What are hooks in React?

Hooks are a new addition in React 16.8. They let developers use state and other React features

without writing a class. Hooks doesn’t violate any existing React concepts. Instead, Hooks provide a

direct API to react concepts such as props, state, context, refs and life-cycle

37. Explain the useState hook in React?

The most used hook in React is the useState() hook. Using this hook we can declare a state variable

inside a function but only one state variable can be declared using a single useState() hook. Whenever

the useState() hook is used, the value of the state variable is changed and the new variable is stored

in a new cell in the stack.

Syntax:

const [state, setState] = useState(initialState);

 state: The current state value.

 setState: A function used to update the state value.

 initialState: The initial value of the state.

38. Explain the useEffect hook in React?

The useEffect hook in React eliminates the side effect of using class based components. It is used as

an alternative to componentDidUpdate() method. The useEffect hook accepts two arguments where

second argument is optional.

useEffect(function, dependency)

The dependency decides when the component will be updated again after rendering.
39. What is React Fragments?

when we are trying to render more than one root element we have to put the entire content inside the

‘div’ tag which is not loved by many developers. So since React 16.2 version, Fragments were

introduced, and we use them instead of the extraneous ‘div’ tag. The following syntax is used to create

fragment in react.

<React.Fragment>

<h2>Child-1</h2>

<p> Child-2</p>

</React.Fragment>

40. What is a react developer tool?

React Developer Tools is a Chrome DevTools extension for the React JavaScript library. A very useful

tool, if you are working on React applications. This extension adds React debugging tools to the

Chrome Developer Tools. It helps you to inspect and edit the React component tree that builds the

page, and for each component, one can check the props, the state, hooks, etc.

41. How to use styles in ReactJS?

CSS modules are a way to locally scope the content of your CSS file. We can create a CSS module

file by naming our CSS file as App.modules.css and then it can be imported inside App.js file using

the special syntax mentioned below.

Syntax:

import styles from './App.module.css';

42. Explain styled components in React?


Styled-component Module allows us to write CSS within JavaScript in a very modular and reusable

way in React. Instead of having one global CSS file for a React project, we can use styled-component

for enhancing the developer experience. It also removes the mapping between components and styles

– using components as a low-level styling construct

The command to install styled components is

npm i styled-components

Using the below code we can custom style a button in React

import styled from 'styled-components'

const Button = styled.div`

width : 100px ;

cursor: pointer ;

text-decoration : none;

export default Button;

43. What is prop drilling and its disadvantages?

Prop drilling is basically a situation when the same data is being sent at almost every level due to

requirements in the final level. The problem with Prop Drilling is that whenever data from the Parent

component will be needed, it would have to come from each level, Regardless of the fact that it is not

needed there and simply needed in last.


44. What is conditional rendering in React?

Conditional rendering in React is used when you want to render different UI elements based on certain

conditions. For example, rendering a login button if a user is not logged in or rendering a logout button

when the user is logged in.

const isLoggedIn = true;

return (

<div>

{isLoggedIn ?<button>Logout</button> : <button>Login</button>}

</div>

);

45. What are controlled components in React?

Controlled components are React components where the form data is handled by the state within the

component. The form element's value is controlled via the React state, making the form elements

responsive to changes.

For further reading, check out our dedicated article on Intermediate ReactJS Intermediate Interview

Questions. Inside, you’ll discover over 20 questions with detailed answers.

React Interview Questions for Experienced

Here, we cover advanced react interview questions with answers for experienced professionals,

who have over 5+ years of experience.

46. What is custom hooks in React?


Custom hooks are normal JavaScript functions whose names start with “use” and they may call other

hooks. We use custom hooks to maintain the DRY concept that is Don’t Repeat Yourself. It helps us

to write a logic once and use it anywhere in the code.

47. How to optimize a React code?

We can improve our react code by following these practices:

 Using binding functions in constructors

 Eliminating the use of inline attributes as they slow the process of loading

 Avoiding extra tags by using React fragments

 Lazy loading

48. What is the difference between useref and createRef in React ?

Here is the difference table of useref and createRef in React

useRef createRef

It is a hook. It is a function.

It uses the same ref throughout the component's It creates a new ref every time component

lifecycle. re-renders.

It saves its value between re-renders in a functional


It creates a new ref for every re-render.
component.
useRef createRef

It returns a read-only ref object (cannot be


It returns a mutable ref object (i.e., can be changed).
modified directly).

Used for accessing DOM elements, persisting


Used for class components, especially
values, or managing timers in functional
when referencing DOM elements.
components.

const myRef = useRef(); const myRef = React.createRef();

49. What is react-redux?

React-redux is a state management tool which makes it easier to pass these states from one

component to another irrespective of their position in the component tree and hence prevents the

complexity of the application. As the number of components in our application increases it becomes

difficult to pass state as props to multiple components. To overcome this situation we use react-redux

50. What are benefits of using react-redux?

They are several benfits of using react-redux such as:

 It provides centralized state management i.e. a single store for whole application

 It optimizes performance as it prevents re-rendering of component

 Makes the process of debugging easier

 Since it offers persistent state management therefore storing data for long times become easier
51. Explain the core components of react-redux?

There are four fundamental concepts of redux in react which decide how the data will flow through

components

 Redux Store: It is an object that holds the application state

 Action Creators: These are functions that return actions (objects).

 Actions: Actions are simple objects which conventionally have two properties- type and

payload

 Reducers: Reducers are pure functions that update the state of the application in response to

actions

52. How can we combine multiple reducers in React?

When working with Redux we sometimes require multiple reducers. In many cases, multiple actions

are needed, resulting in the requirement of multiple reducers. However, this can become problematic

when creating the Redux store. To manage the multiple reducers we have function called

combineReducers in the redux. This basically helps to combine multiple reducers into a single unit

and use them.

Syntax

import { combineReducers } from "redux";

const rootReducer = combineReducers({

books: BooksReducer,

activeBook: ActiveBook
});

53. Explain CORS in React?

In ReactJS, Cross-Origin Resource Sharing (CORS) refers to the method that allows you to make

requests to the server deployed at a different domain. As a reference, if the frontend and backend are

at two different domains, we need CORS there.

We can setup CORS evironment in frontend using two methods:

 axios

 fetch

54. What is axios and how to use it in React?

Axios, which is a popular library is mainly used to send asynchronous HTTP requests to REST

endpoints. This library is very useful to perform CRUD operations.

 This popular library is used to communicate with the backend. Axios supports the Promise API,

native to JS ES6.

 Using Axios we make API requests in our application. Once the request is made we get the

data in Return, and then we use this data in our project.

To install axios package in react use the following command.

npm i axios

55. Write a program to create a counter with increment and decrement?

We can create the counter app with increment and decrement by writing the below code in the

terminal:
import React, { useState } from "react";

const App = () => {

const [counter, setCounter] = useState(0)

const handleClick1 = () => {

setCounter(counter + 1)

const handleClick2 = () => {

setCounter(counter - 1)

return (

<div>

<div>

{counter}

</div>

<div className="buttons">
<button onClick={handleClick1}>

Increment

</button>

<button onClick={handleClick2}>

Decrement

</button>

</div>

</div>

export default App

Output:

Counter App using React

56. Explain why and how to update state of components using callback?

It is advised to use a callback-based approach to update the state using setState because it solves

lots of bugs upfront that may occur in the future.We can use the following syntax to update state using

callback
this.setState(st => {

return(

st.stateName1 = state1UpdatedValue,

st.stateName2 = state2UpdatedValue

})

57. What is React-Material UI?

React Material UI is an open-source React component library, offering prebuilt components for

creating React applications. Developed by Google in 2014, it's compatible with JavaScript frameworks

like Angular.js and Vue.js. Renowned for its quality designs and easy customization, it's favored by

developers for rapid development.

58. What is flux architecture in redux?

Flux architecture in Redux is a design pattern used for managing application state in a unidirectional

data flow. In this architecture, actions are dispatched to modify the store, which holds the entire

application state. The store sends the updated state to the view (UI), and the cycle repeats when new

actions are triggered. Redux follows this structure to ensure a predictable and maintainable state

management system for large applications.

59. What are custom hooks in React?

Custom hooks are user-defined functions that use built-in hooks like useState, useEffect, etc., to reuse

stateful logic across components. They allow you to extract and share common logic.

60. How can you optimize React performance?


Optimizing React performance can be achieved using:

 React.memo() for preventing unnecessary re-renders.

 Lazy loading components with React.lazy() and Suspense.

 Using useMemo() and useCallback() hooks to memoize values and functions.

 Avoiding unnecessary state updates.

61. What is the Strict Mode in React?

Strict Mode in React is a tool that helps developers find and fix problems in their app while developing.

It only works in development and doesn’t affect the app when it’s running in production. When enabled,

it checks for potential issues, such as old features that should no longer be used, and gives warnings

to help avoid bugs.

We can enable the strict mode by by wrapping your application or specific components inside

the <React.StrictMode>.

import React from "react";

import ReactDOM from "react-dom";

const App = () => {

return (

<div>

<h1>Hello, World!</h1>
</div>

);

};

ReactDOM.render(

<React.StrictMode>

<App />

</React.StrictMode>,

document.getElementById("root")

);

62. What is Redux and how does it work with React?

Redux is a state management library that helps manage the application state globally. It uses actions,

reducers, and a central store to control state. React-Redux is used to connect Redux state to React

components.

63. How does React handle concurrency?

React's Concurrent Mode is a set of features that help React apps stay responsive and gracefully

adjust to the user’s device capabilities and network speed. It allows React to interrupt rendering and

prioritize high-priority tasks.

64. How does React handle server-side rendering (SSR)?


Server-side rendering (SSR) is the process of rendering a React application on the server and sending

the fully rendered HTML to the client. This improves the initial page load performance and SEO.

65. What are forms in React?

In React, forms are a way to capture user input, such as text fields, checkboxes, radio buttons, and

buttons. React provides controlled and uncontrolled components for handling form elements, allowing

developers to manage user input and form state in an efficient and structured way.

66. How to create forms in React?

Creating forms in React involves handling user input and managing the form's state. In React, form

elements like <input>, <textarea>, and <select> are controlled components, meaning their values are

controlled by the React state.

 Create the State for the Form: Use the useState hook to manage form input values.

 Set the Value of Form Elements: Bind the form elements’ value attribute to the corresponding

state variable to make the inputs controlled.

 Handle User Input: Use an onChange event handler to update the state whenever the user

types in the form fields.

 Submit the Form: Handle the form submission with an onSubmit event, and prevent the

default behavior to stop the page from refreshing.

import React, { useState } from 'react';

function MyForm() {

// State to store input values


const [name, setName] = useState('');

const [email, setEmail] = useState('');

const [message, setMessage] = useState('');

// Handle input change for each field

const handleNameChange = (e) => setName(e.target.value);

const handleEmailChange = (e) => setEmail(e.target.value);

const handleMessageChange = (e) => setMessage(e.target.value);

// Handle form submission

const handleSubmit = (e) => {

e.preventDefault(); // Prevent default form submission behavior

console.log('Form submitted:', { name, email, message });

};

return (

<form onSubmit={handleSubmit}>

<div>
<label>Name:</label>

<input type="text" value={name} onChange={handleNameChange} />

</div>

<div>

<label>Email:</label>

<input type="email" value={email} onChange={handleEmailChange} />

</div>

<div>

<label>Message:</label>

<textarea value={message} onChange={handleMessageChange} />

</div>

<button type="submit">Submit</button>

</form>

);

export default MyForm;

Output:
React Form

67. What is Lazy Loading in React?

Lazy Loading in React is a technique used to load components only when they are needed, instead

of loading everything at once when the app starts. This helps improve the performance of the app by

reducing the initial loading time.

In React, React.lazy() is used to implement lazy loading for components, which allows you to split

your code into smaller bundles and load them only when required.

68. How is React different from React Native?

React React Native

A JavaScript library for building user A framework for building mobile applications using

interfaces, primarily for web applications. JavaScript and React.

Focuses on developing native mobile applications


Focuses on developing web applications.
for iOS and Android.
React React Native

Renders native mobile components using native


Renders HTML using the Virtual DOM.
APIs (e.g., View, Text, Image).

Uses web technologies like HTML, CSS, Uses native mobile components and styles for

and JavaScript. building mobile UIs.

Runs on mobile devices and communicates with


Runs in the browser on a web server.
native code.

Can be deployed on browsers like Chrome, Can be deployed as native apps on iOS and Android

Firefox, etc. platforms.

69. What is Memoization in React?

Memoization in React is an optimization technique used to improve the performance of a component

by preventing unnecessary re-renders. It involves caching the results of expensive function calls and

reusing the cached result when the inputs to the function haven't changed. This is particularly useful

when a component’s rendering process is slow, and you want to avoid recalculating or re-rendering

unnecessarily.

How Memoization Works in React:

React provides two key APIs for memoization:

1. React.memo(): This is a higher-order component (HOC) used to prevent re-renders of

functional components if their props have not changed.


2. useMemo(): A hook that memorizes the result of a computation and only recomputes it when

its dependencies change.

70. What is Reoncillation in React?

Reconciliation in React is the process of updating the DOM when a component's state or props

change. React uses the Virtual DOM to efficiently determine what parts of the actual DOM need to

be updated. Here's a simplified overview:

 Triggering Reconciliation: React triggers reconciliation when state or props change (e.g.,

through setState() or useState()).

 Virtual DOM Diffing: React compares the old Virtual DOM with the new one to identify

changes.

 Efficient Updates: React calculates the minimal set of changes and applies them to the real

DOM.

 Fiber Algorithm: React's Fiber algorithm allows the reconciliation process to be interrupted

and prioritized, improving performance for complex tasks.

Top 10 Commonly Asked ReactJS Interview Questions

1. What is React?

2. What are the key features of React?

3. What is the Virtual DOM, and how does it work?

4. What are React components?

5. What is the difference between a functional component and a class component in

React?
6. What are React Hooks?

7. What is useState in React?

8. What are Custom Hooks?

9. What is JSX?

10. What is the difference between props and state in React?

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy