Download as pdf or txt
Download as pdf or txt
You are on page 1of 158

#_ Top 50 React Interview Questions

Q1. What is the role of React in software development?


Answer: React is a JavaScript library used primarily for building
interactive user interfaces for web applications. It allows developers
to create reusable UI components and manage the application state
efficiently.

Q2. What is React?

Answer: React is an open-source JavaScript library developed by


Facebook for building user interfaces, especially for single-page
applications. It enables developers to build UI components that can
manage their own state.

Q3. What is SPA (Single Page Application)?

Answer: A SPA is a web application or website that interacts with the


user by dynamically rewriting the current page rather than loading
entire new pages from the server. This results in a more fluid and
faster user experience.

Q4. What are the advantages of React?

Answer:

● Component-based architecture
● Virtual DOM for efficient updates
● Reusable components
● Strong community support
● Integration capability with various backends
● Concurrent mode for smoother UI interactions

Q5. What are the disadvantages of React?

Answer:

● Learning curve for beginners

By: Waleed Mousa


● JSX can be confusing for some
● Requires understanding of the component lifecycle and state
management
● Dependency on third-party libraries for routing, state management,
etc.

Q6. What is the difference between React and Angular?

Answer: React is a library focused on building UI components while


Angular is a full-fledged MVC framework. Angular includes features like
dependency injection, routing, and two-way data binding out of the box,
whereas React often relies on third-party libraries for these.

Q7. What is DOM?

Answer: DOM (Document Object Model) is a programming API for web


documents. It represents the structure of a document as a tree of
objects, with each object corresponding to a part of the document, such
as an element or attribute.

Q8. What is the difference between DOM and Virtual DOM?

Answer: The Virtual DOM is a lightweight in-memory representation of


the actual DOM elements. The rendering engine can quickly make changes
to the Virtual DOM and then subsequently update the real DOM in a more
efficient and optimized manner.

Q9. What are React Components?

Answer: React Components are reusable pieces of the UI that can manage
their own state, structure, and rendering. They can be class-based or
functional and are the building blocks of a React application.

Q10. How to setup a react project?

Answer: You can set up a React project using

npx create-react-app project-name

By: Waleed Mousa


Q11. What is npm? What is the role of node_modules folder?

Answer: npm (Node Package Manager) is a package manager for JavaScript.


The node_modules folder contains all the modules and libraries your
project depends on, installed via npm.

Q12. What is the role of the public folder in React?

Answer: The public folder contains assets that are publicly available,
like the index.html file, images, or other static files that aren't
processed by Webpack.

Q13. What is the role of the src folder in React?

Answer: The src folder contains the main source code for your React
application, including components, styles, and logic.

Q14. What is the role of the index.html page in React?

Answer: index.html is the main HTML file that gets loaded in the
browser. It contains the root div (<div id="root"></div>) where the
React application gets mounted.

Q15. What is the role of App.js file in React?

Answer: App.js typically serves as the root component for a React


application. It often contains the main layout and wraps other
components.

Q16. What is the role of function and return inside App.js?

Answer: The function inside App.js defines the App component, and the
return statement describes what the UI looks like for that component
using JSX.

By: Waleed Mousa


Q17. Can we have a function without return inside App.js?

Answer: Yes, but if a function in App.js is intended as a React


component, it must return something (either JSX or null). Functions
without a return statement in React components will throw an error.

Q18. What is the role of export default inside App.js?

Answer: export default allows the App component to be imported and used
in other files/modules.

Q19. What is the role of index.js file, ReactDOM, and render method in React?

Answer: index.js is the entry point to a React application. ReactDOM


provides DOM-specific methods, and the render method is used to render a
React component to a DOM node.

Q20. How does a React App load and display the components in the browser?

Answer: React uses ReactDOM's render method to mount the root component
(often App) to the root div in index.html. From there, components are
nested, and React efficiently updates and renders only the necessary
components when data changes.

Q21. What is JSX?

Answer: JSX (JavaScript XML) is a syntax extension for JavaScript that


allows you to describe the UI structure in a way that looks similar to
HTML.

Q22. What are the advantages of JSX?

Answer:

● Makes the code more readable


● Allows for the co-location of structure, style, and behavior
● Provides a concise syntax to define element tree structures

By: Waleed Mousa


Q23. Can a browser read a JSX file? What is Babel?

Answer: No, browsers can't directly read JSX. Babel is a JavaScript


compiler that transforms JSX (and other modern JS features) into plain
JavaScript that browsers can understand.

Q24. What is a Transpiler?

Answer: A transpiler (or source-to-source compiler) takes the source


code written in one language and transforms it into another language.
Babel is an example that transpiles JSX and modern JavaScript into
older JavaScript versions for wider compatibility.

Q25. Is it possible to use JSX without React?

Answer: While JSX is closely associated with React, it's not exclusive
to it. JSX is just a syntax, so it can be used with other libraries or
frameworks if they provide a mechanism to transform it, though this is
less common.

Q26. What is a fragment in React?

Answer: Fragments let you group multiple elements without adding an


extra node to the DOM. It's a way to return multiple elements without
wrapping them in a container div.

Q27. How do you iterate over a list in JSX? What is the use of the map
method?

Answer: You can use the map method to iterate over a list in JSX. It
allows you to transform each item in an array and typically results in
an array of JSX elements.

const items = ['A', 'B', 'C'];


return items.map(item => <div key={item}>{item}</div>);

By: Waleed Mousa


Q28. What are props in JSX?

Answer: Props (short for "properties") are a way to pass data from
parent to child components. They are read-only and help components to
be reusable.

Q29.What is the spread operator?


Answer: The spread operator (...) allows an iterable like an array or
object to be expanded in places where zero or more arguments (for
function calls) or elements (for array literals) are expected, or
key-value pairs (for object literals) are expected.

Q30. What are the types of conditional rendering in JSX?

Answer: There are several ways to conditionally render in JSX:

1. Ternary Operator:

condition ? <ComponentA /> : <ComponentB />

2. Short-Circuit Evaluation:

condition && <Component />

3. If/Else Statements: This is not directly inside JSX, but you can
use if/else logic before the return statement to decide which
component to render.
4. Switch/Case: Similar to if/else, but can be useful when you have
multiple conditions to check.
5. IIFE (Immediately Invoked Function Expression):

{(() => {

if (condition) return <ComponentA />;

return <ComponentB />;

})()}

These methods allow for more dynamic rendering based on the


application's state, props, or other factors.

By: Waleed Mousa


Q31. What is the difference between state and props?
Answer: Props are immutable data passed from parent to child
components, while state is mutable data managed within a component,
representing the component's internal state.

Q32. What are React hooks?

Answer: React hooks are functions introduced in React 16.8 that allow
you to use state and other React features without writing a class
component. Examples include useState, useEffect, and useContext.

Q33. What is the useState hook and how does it work?

Answer: useState is a hook that lets you add React state to functional
components. It returns an array where the first element is the current
state, and the second element is a function to update that state.

Q34. How does the useEffect hook work?

Answer: useEffect lets you perform side effects in functional


components. It's similar to lifecycle methods like componentDidMount,
componentDidUpdate, and componentWillUnmount in class components.

Q35. What is context in React?

Answer: The Context API in React provides a way to pass data through
the component tree without having to pass props manually at every
level. It's useful for sharing data that can be considered "global",
such as themes, user authentication, etc.

Q36. What is Redux and how is it related to React?

Answer: Redux is a predictable state container for JavaScript apps.


While it can be used with any library or framework, it's often used
with React to manage the application state outside of the component
tree.

By: Waleed Mousa


Q37. How does React handle forms?

Answer: React forms are typically controlled. This means the form data
is handled by the React component's state and not by the DOM directly.
Input changes are captured by event handlers which then update the
component state.

Q38. What are controlled and uncontrolled components?

Answer: In React, a controlled component's form data is controlled by


the state, whereas an uncontrolled component's form data is controlled
by the DOM itself.

Q39. What are higher-order components (HOCs)?

Answer: HOCs are a pattern in React where a component wraps another


component to extend its behavior or props. It's a way to reuse
component logic.

Q40. What is React Router?

Answer: React Router is a third-party library that provides routing


capabilities to React apps. It helps in defining multiple routes,
navigating between them, and rendering specific components based on the
current route.

Q41. What are React Portals?

Answer: React Portals provide a way to render children into a DOM node
outside of the parent DOM hierarchy, useful for modals, popups, or any
UI overlay that should be above other content.

Q42. How do you handle errors in React?

Answer: With React 16 and above, you can handle errors using Error
Boundaries. An error boundary is a React component that catches
JavaScript errors anywhere in its child component tree and renders a
fallback UI.

By: Waleed Mousa


Q43. What are keys in React lists and why are they important?

Answer: Keys are special string attributes you should include when
creating lists of elements in React. They help React identify which
items have changed, are added, or are removed, which in turn helps in
efficiently re-rendering lists.

Q44. What is the Virtual DOM reconciliation?

Answer: Reconciliation is the process by which React updates the DOM by


making changes based on the difference between the current and the
previous state. It involves diffing the old and new Virtual DOMs and
only updating what's necessary in the real DOM.

Q45. How can you optimize a React application?

Answer: Some common optimizations include:

● Using React.memo for functional components.


● Implementing shouldComponentUpdate for class components.
● Lazy loading components using React.lazy.
● Using virtualized lists for large lists.
● Avoiding unnecessary re-renders using tools like useCallback and
useMemo.
● Profiling the app using the React DevTools.

Q46. How do you handle asynchronous operations in React?

Answer: Asynchronous operations can be handled using JavaScript


promises, async/await, or third-party libraries like Axios. With hooks,
useEffect is often used to trigger async operations, and the state can
be updated upon resolving the operations.

Q47. What is prop drilling and how can you avoid it?

Answer: Prop drilling refers to the process of passing data from one
part of the React component tree to another by going through other

By: Waleed Mousa


parts that do not need the data. It can be avoided using the Context
API, Redux, or other state management libraries.

Q48. How do you implement CSS in React components?

Answer: There are several ways:

● Inline styles using a JavaScript object.


● Traditional CSS classes via separate CSS files.
● CSS-in-JS libraries like styled-components or emotion.
● CSS Modules to locally scope CSS by default.

Q49. How can you integrate TypeScript with React?

Answer: TypeScript can be integrated into a React project by configuring


the TypeScript compiler, using .tsx extensions for React components,
and adding type definitions for React and other libraries.

Q50. What are React lifecycle methods and how are they used?

Answer: Lifecycle methods are special methods in class components that


automatically get called as your component achieves certain milestones
in its life in the DOM. They include methods like componentDidMount,
componentDidUpdate, and componentWillUnmount. They're used for various
purposes like fetching data, setting up subscriptions, or manually
manipulating the DOM.

By: Waleed Mousa


REACT
CHEAT SHEET
YIHUA ZHANG

V1.02
HEEELLLOOOOO!

I’m Andrei Neagoie, Founder and Lead Instructor of the Zero To Mastery Academy.

After working as a Senior Software Developer over the years, I now dedicate 100% of my time to
teaching others in-demand skills, help them break into the tech industry, and advance their
careers.

In only a few years, over 1,000,000 students around the world have taken Zero To Mastery courses
and many of them are now working at top tier companies like Apple, Google, Amazon, Tesla, IBM,
Facebook, and Shopify, just to name a few.

This cheat sheet, created by our React instructor (Yihua Zhang) provides you with the key React
information and concepts that you need to know.

If you want to not only learn React but also get the exact steps to build your own projects and get
hired as a Frontend or Fullstack Developer, then check out our Career Paths.

Happy Coding!
Andrei

Founder & Lead Instructor, Zero To Mastery


Andrei Neagoie
React Cheatsheet
Table of Contents
JSX

React Elements
React Element Tags
React Element Attributes

React Elements Embedded Javascript


React Element Inline Styles
React Fragments

React Components
Functional Components
Component Props
The Children Prop
Conditional Rendering
Lists in Components
Memo
Context

Hooks
useState

useEffect

useLayoutEffect
useRef
useCallback

useMemo

React Cheatsheet 1
useContext

Class Component
Constructor

State

Lifecycle Methods
componentDidMount

componentWillUnmount
componentDidUpdate

Error Boundaries
getDerivedStateFromError
componentDidCatch

Useful Links

React Cheatsheet 2
JSX
Almost all React code is written in JSX. JSX is a syntax extension of Javascript that
allows us to write HTML-like syntax in Javascript.

React Elements
React Element Tags
React elements look just like HTML, in fact they render the same equivalent HTML
elements.

<h1>My Header</h1>
<button>My Button</button>
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
</ul>

Single tag elements like the img element and the br element must be closed like so

<img src="my-image-source.jpeg" />


<br />

React Element Attributes


React elements have different attributes compares to their HTML counterparts. Since JSX
is still javascript, we use camelcase. Also, class is a protected keyword in javascript
(creating classes) so the HTML class attribute in JSX is className .

<div className="my-container">
<img className="my-container-image" src="my-image.jpeg"/>
</div>

React Cheatsheet 3
React Elements Embedded Javascript
The power of JSX is that it’s javascript and HTML. This means you can write javascript to
render different attributes directly in your javascript using curly braces {} .

const divClass = "my-div-class"

<div className={divClass}></div>

React Element Inline Styles


React elements just like HTML elements can use the style attribute, but you pass them
as javascript objects instead of double quote strings.

In HTML

<h1 style="color:blue;text-align:center">This is a header</h1>

In JSX

<h1 style={{ color: 'blue', textAlign: 'center' }}>This is a header</h1>

React Fragments
React has a special element called a fragment. It’s a special element that doesn’t actually
render into the DOM, but can act as a parent to a group of elements.

import { Fragment } from 'react'

<Fragment>
<h1> My H1 </h1>
<p> My Paragraph </p>
</Fragment>

If you don’t want to import Fragment from the React library, you can also use <> .

<>
<h1> My H1 </h1>
<p> My Paragraph </p>
</>

React Cheatsheet 4
Fragments are useful in components since components require us to return one parent
level element, and if we don’t want to needlessly add HTML elements to our website, we
can just use fragments.

React Components
Components are the building blocks of your web application. We use them to organize
groups of React elements together so they’re reusable. There are two kinds of
components, class components and functional components but functional components
are the de facto standard today. They both follow the same two rules:

1. Component names must be capitalized i.e. MyComponent instead of myComponent

2. They must return JSX, more specifically one parent level JSX element (more on this
later).

Functional Components
Functional components are just javascript functions that return JSX.
Here's how you create a functional component using function declaration:

function MyComponent() {
return <h1>My Component</h1>
}

You can also use an arrow function:

const MyComponent = () => {


return <h1>My Component</h1>
}

The component can then be used like any React element.

const MyComponent = () => {


return <h1>My Component</h1>
}

const MyOtherComponent = () => {


return (

React Cheatsheet 5
<div>
<MyComponent />
<p> Sample Text </p>
</div>
)
}

Component Props
We can pass data to our components through custom attributes on the component
element. We can choose any name for the attribute as long they don’t overlap with the
existing general element attributes (i.e. className , styles , onClick etc.). These properties
are then grouped into an object where the attribute name is the key, and the value is the
value. Here we are passing a prop title from the App component to our component
MyComponent .

const MyComponent = (props) => {


return <h1>{props.title}</h1>
}

const App = () => {


return (
<MyComponent title="Hello World" /> // Props == { title: "Hello World" }
)
}

Remember, you can embed any of the values in your props object in JSX since it’s just
javascript, just remember to use curly braces ( {} ).
Since the props are just an object, it’s common to destructure the values for cleaner,
simpler code.

const MyComponent = ({title}) => {


return <h1>{title}</h1>
}

const App = () => {


return (
<MyComponent title="Hello World" />
)
}

React Cheatsheet 6
Any JavaScript value can be passed as a prop such as arrays, objects, other elements
and components!

The Children Prop


All component have a special prop called children . Any data (usually components and
react elements) sitting between the opening and closing tags of the component get
passed in as children .

const Greeting = ({ children }) => {


return children //<h1> Hello World! </h1>
}

const App = () => {


return (
<Greeting>
<h1>Hello World!</h1>
</Greeting>
)
}

We can render it anywhere in our component’s JSX! Just remember that it’s a javascript
variable so make sure it’s wrapped in curly braces {} .

const GreetingCard = ({ children }) => {


return (
<div>
<h1> Greetings! </h1>
{children}
</div>
)
}

const App = () => {


return (
<GreetingCard>
<p>Example Children Paragraph</p>
<button> Example Children Button</button>
</GreetingCard>
)
}

React Cheatsheet 7
Conditional Rendering
Since our components are written in JSX which is just javascript, we can conditionally
render different things with javascript. A basic example is to use an if statement in our
functional component.

const Greeting = ({large}) => {


if(large) {
return <h1> Hello World! </h1>
}
return <p> Hello World! </p>
}

const App = () => {


return (
<div>
<Greeting large={true}/> // <h1> Hello World! </h1>
<Greeting large={false}/> // <p> Hello World! </p>
</div>
)
}

We can also use a ternary operator!

const Greeting = ({large}) => {


return (large ? <h1> Hello World! </h1> : <p> Hello World! </p>)
}

const App = () => {


return (
<div>
<Greeting large={true}/> // <h1> Hello World! </h1>
<Greeting large={false}/> // <p> Hello World! </p>
</div>
)
}

In a component, if we return null nothing will render to the DOM.

const Greeting = ({display, message}) => {


return ( display ? <h1> {message} </h1> : null )
}

const App = () => {


return (
<div>
<Greeting message="rendered!" display={true}/> // <h1> rendered! </h1>

React Cheatsheet 8
<Greeting message="not rendered!" display={false}/> // nothing rendered
</div>
)
}

Lists in Components
If we want to duplicate elements/components, we can do so by looping through an array
with the .map() method as long as we return JSX from the callback.
Remember, this is javascript so wrap your map call in {} . We must remember to add the
attribute key to the top level JSX element we return from map ; the value must also be a
unique value for each iteration.

const ShoppingList = ({items}) => {


return (
<ul>
{items.map((item) => <li key={item}> {item} </li>)}
</ul>
)
}

const App = () => {


const groceries = ['broccoli', 'carrots', 'chicken', 'garlic'];
return <ShoppingList items={groceries} />
}

IMPORTANT REMINDER
Remember, when mapping over an array into JSX, you must include a key attribute with
a unique value. It’s tempting to use the index from map but this may cause issues down
the road.

const ShoppingList = ({items}) => {


return (
<ul>
// DON'T DO THIS
{items.map((item, idx) => <li key={idx}> {item} </li>)}
</ul>
)
}

const App = () => {


const groceries = ['broccoli', 'carrots', 'chicken', 'garlic'];
return <ShoppingList items={groceries} />
}

React Cheatsheet 9
The reason is because React uses the key to determine which components to re-render,
with the keys themselves being unique identifiers hence why the values need to be
unique. Indexes are just numbers and in lists where there are multiple maps, if you always
use the index as the key React may get confused.

const ShoppingList = () => {


const vegetables = ['broccoli', 'carrots', 'garlic'];
const meats = ['chicken', 'beef']

return (
<ul>
{vegetables.map((veg, idx) => <li key={idx}> {veg} </li>)}
{meats.map((meat, idx) => <li key={idx}> {meat} </li>)}
</ul>
)
}

As you can see in the above example, the map of vegetables has indexes 0, 1 and 2
since there are 3 items. The map for meats will be have index 0 and 1 since there are 2
items. This is a problem since React can’t differentiate the vegetable item with key 0 and
the meat item with key 0, or the vegetable item with key 1 and the meat item with key 1.
This is why we need to use unique keys !
Below we can fix this using the name attribute, which we know are unique.

const ShoppingList = () => {


const vegetables = ['broccoli', 'carrots', 'garlic'];
const meats = ['chicken', 'beef']

return (
<ul>
{vegetables.map((veg) => {<li key={veg}> {veg} </li>})}
{meats.map((meat) => {<li key={meat}> {meat} </li>})}
</ul>
)
}

Memo
Use react.memo allows a component to skip re-rendering if it’s props haven’t
changed when it’s parent re-renders.

React Cheatsheet 10
When a component re-renders, all its child components will also re-render. Wrapping a
component in react.memo will prevent that component re-rendering caused by upstream
re-renders if the props have not changed.

const MemoizedComponent = memo(SomeComponent, arePropsEqual?)

react.memo take two arguments:

1. The functional component we want to memoize.

2. An optional function that determines if the component should re-render. It receives


two arguments, the component’s previous props and its new props.

import { memo } from 'react'

const MemoizedComponent = memo(


function SomeComponent(props) {},
(prevProps, nextProps) => { //return true or false }
)

The second argument is a custom comparison function that for the majority of
circumstances are not needed. When not passed a second argument, react defaults to
shallow comparison of the old props and new props with Object.is . If you need custom
comparison, the function should return true if the props are equal and therefore not re-
render. Or it should return false if the props are not equal and should re-render.

Context
If we had some data values we wanted to share across multiple sibling or nested child
components, we would have to lift that data up to a commonly shared parent and
needlessly drill it down through multiple components and their props. Take the following
example

const GrandChildA = ({ text }) => { // I need text


return (
<div>
<h1> Grand Child A </h1>
<p> {text} </p>
</div>
)
}

React Cheatsheet 11
const ChildA = ({ text }) => { // I don't need text
return (
<div>
<h1> Child A </h1>
<GrandChildA text={text} />
</div>
)
}

const ParentA = ({ text }) => { // I don't need text


return (
<div>
<h1> Parent A </h1>
<ChildA text={text} />
</div>
)
}

const ChildB = ({ text }) => { // I need the text


return (
<div>
<h1> Child B </h1>
<p> {text} </p>
</div>
)
}

const ParentB = ({ text }) => { // I don't need text


return (
<div>
<h1> Parent B </h1>
<ChildB text={text} />
</div>
)
}

const App = () => {


const text = "Hello World";

return (
<div>
<h1> App </h1>
<ParentA text={text} />
<ParentB text={text} />
</div>
)
}

Here, we have to pass the text value from the App component all the way through Parent
A and ChildA just so GrandChildA can receive it, even though ParentA and ChildA don’t

need the text other than to pass it down. The same is true for ParentB in order to get the
text value to ChildB . This is called prop drilling.

React Cheatsheet 12
We can’t move the text value down the tree since both GrandChildA and ChildB need it,
and App is the lowest common parent between them. This makes our code extremely
brittle since moving and the components serving to pass the text prop needlessly
complex.

We can solve this with React Context which allows us to lift the data into a special
component called Context that allows any of it’s children no matter where they are to
access it’s values without the need for prop drilling.
We need the createContext function from React and pass it the initial value we want to
share. It returns us back an object that contains two components:

1. the Provider component which we wrap around the portion of the component tree we
want to access the value.

2. The Consumer component which has access to the values from the created context
which we place in any component that needs the value.

import { createContext } from 'react';

const TextContext = createContext('');

const GrandChildA = () => { // I need text


return (
<div>
<h1> Grand Child A </h1>
<TextContext.Consumer>
{text => <p> {text} </p>}
</TextContext.Consumer>
</div>
)
}

const ChildA = () => { // I don't need text


return (
<div>
<h1> Child A </h1>
<GrandChildA />
</div>
)
}

const ParentA = () => { // I don't need text


return (
<div>
<h1> Parent A </h1>
<ChildA />
</div>
)

React Cheatsheet 13
}

const ChildB = () => { // I need the text


return (
<div>
<h1> Child B </h1>
<TextContext.Consumer>
{text => <p> {text} </p>}
</TextContext.Consumer>
</div>
)
}

const ParentB = () => { // I don't need text


return (
<div>
<h1> Parent B </h1>
<ChildB />
</div>
)
}

const App = () => {


return (
<TextContext.Provider value="Hello World">
<ParentA />
<ParentB />
</TextContext.Provider>
)
}

Hooks
Hooks were introduced in React version 16.8 as a way to extend additional functionality
into functional components. Previously this functionality was only available to class
components, but through hooks we can super charge our functional components!

To better understand hooks, we need to understand the React component lifecycle. There
are three main phases of any React component:

1. The mounting phase when a component is created and inserted into the DOM. This is
the initial render and only happens once in a components lifecycle.

2. The updating phase is when a component re-renders due to updates. This happens
either due to prop changes or state changes (more below).

React Cheatsheet 14
3. The final phase is the un-mounting phase, when a component is removed from the
DOM.

Hooks are normally called at the top of our components.

useState
useStatehook allows us to store values scoped to a component. Any changes to
those values will cause the component and any of it’s child components to re-
render.

As mentioned above, components re-render in the updating phase (2) due to prop
changes and state changes. State is data stored inside of a component that can be
updated/changed. When this state data changes, this will trigger a re-render of the
component. While we can store and change data in a variable, those changes will not
trigger a re-render. With the useState hook, it does allow us to trigger re-renders on
changes to that data.
useState is a function that we can pass an optional argument representing the initial value
we want to store. The useState hook returns back an array containing two values, the first
is the current state value, the second is a setter function to update this state value.

import { useState } from 'react';

const MyComponent = () => {


const [value, setValue] = useState(initialValue);
}

The setValue function we de-structured is called the setter function. When we call this
setter function, we pass it the new value we want to set the state to.

Let’s look at a basic counter example.

import { useState } from 'react';

const Counter = () => {


const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);

return (
<div>
{count}
<button onClick={increment}> increment </button>

React Cheatsheet 15
<button onClick={decrement}> decrement </button>
</div>
)
}

Whenever setCount is called, the Counter component will re-render, which is the
behaviour we want since count is has updated and we want our DOM to display the new
value.
It’s important to note that the setter function from useState is asynchronous. This means
that if you try to log the state immediately after setting it, you might not see the updated
state.

useEffect
is a hook that allows us to create side effects in our functional
useEffect

components.
useEffect takes two arguments:

1. The first argument is a callback function called the effect function that contains the
side effect code we want to run.

2. The second argument is an array called the dependency array which contains values
from outside the scope of the effect function. Whenever one of these values changes,
useEffect will run the effect function.

import { useEffect } from 'react'

const MyComponent = () => {


useEffect(() => {
// side effect code here
}, [// dependencies go here]);
}

The effect function will run

1. Once when the component mounts.

2. Whenever any value in the dependency array changes.

A common use case for useEffect is to fetch some data and store it in a state variable.

React Cheatsheet 16
import { useState, useEffect } from 'react'

const UserList = () => {


const [userList, setUserList] = useState([]);

useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => setUserList(users))
}, []);

return (
<div>
{ userList.map(user => <h2 key={user.id}> {user.name} </h2>) }
</div>
)
}

Passing an empty dependency array will only call our effect function once during the
mounting phase since there are no dependencies to react to.
The effect function will run every time a value in the dependency array changes. Values
the effect function relies on but comes from outside of it’s scope are added to the
dependency array. These include props:

import { useState, useEffect } from 'react'

const UserList = ({sourceURL}) => {


const [userList, setUserList] = useState([]);

useEffect(() => {
fetch(sourceURL)
.then(response => response.json())
.then(users => setUserList(users))
}, [sourceURL]);

return (
<div>
{ userList.map(user => <h2 key={user.id}> {user.name} </h2>) }
</div>
)
}

As well as other state variables:

React Cheatsheet 17
import { useState, useEffect } from 'react';

import User from '../components/user';


import { userAPI } from '../api/userAPI';

const UserList = () => {


const [userName, setUserName] = useState('');
const [user, setUser] = useState(null);

const handleTextChange = (event) => {


setUserName(event.target.value);
}

useEffect(() => {
userAPI.getByUsername(userName)
.then(user => setUser(user))
}, [userName]);

return (
<div>
<h2> Search by username </h2>
<input type='text' onChange={handleTextChange} />
<User user={user} />
</div>
)
}

If we want to run a callback when the component unmounts, we can do so by returning


that callback from the effect function. This is useful for cleanup functions that need to
undo effects like subscriptions.

useEffect(() => {
ChatAPI.subscribeToUser(userID);

return () => { // This function runs on unmount


ChatAPI.unsubscribeFromUser(userID);
};
}, []);

It’s important to note, the effect function runs after React renders/re-renders the
component to ensure our effect callback does not block browser painting.

useLayoutEffect
The useLayoutEffect hook is almost identical to the useEffect hook except it runs the
effect callback immediately after DOM changes.

React Cheatsheet 18
The one key difference between the useLayoutEffect hook and useEffect hook:
useLayoutEffect runs the effect callback synchronously immediately after React has

performed all DOM mutations, but before the browser has a chance to paint. This is useful
if you need to make DOM mutations and don't want the screen to flicker between renders.

import { useLayoutEffect } from 'react'

const MyComponent = () => {


useLayoutEffect(() => {
// side effect code here
}, [// dependencies go here]);
}

useRef
useRef is a hook that stores a value in a component like useState except changes to
that value won’t cause the component to re-render.
It accepts one argument as the initial value and returns a reference object.

import { useRef } from 'react';

const MyComponent = () => {


const ref = useRef(initialValue);

// ...remaining component code


}

The value of ref is:

{
current: initialValue
}

We can access and mutate the current value of the ref through the ref.current property.
This value will persist across re-renders.

import { useRef } from 'react';

export default function Counter() {


let ref = useRef(0);

React Cheatsheet 19
function handleClick() {
ref.current = ref.current + 1;
}

return (
<>
<h1>count: {ref.current} </h1>
<button onClick={handleClick}>
Click me!
</button>
</>
);
}

Every time we click the button and trigger handleClick , we are incrementing the
ref.current value. However, because this mutation does not trigger the component to re-

render, so the count does not update in the DOM even though the stored value is
updating.
It is common to store DOM node references in a ref.

import { useRef, useEffect } from 'react';

function InputFocus() {
const inputRef = useRef();

useEffect(() => {
inputRef.current.focus();
}, []);

return (
<input
ref={inputRef}
type="text"
/>
);
}

When the InputFocus component mounts, we will call on the DOM node for the input and
automatically focus it.

useCallback
The useCallback hook is a performance improvement hook that prevents functions
from being needlessly recreated between re-renders.

React Cheatsheet 20
Whenever a component renders or re-renders, any functions that are created are
recreated. In the component below, we create a hideUser function that we use in the
button.

The useCallback hook signature takes two arguments:

1. The function we want to persist between re-renders.

2. A dependency array containing values that tells useCallback when to recreate the
function when any of them change.

import { useMemo } from 'react'

const MyComponent = () => {


const computedValue = useMemo(
() => { //...computationally expensive function },
[//dependencies]
)
}

Looking at an example

import { useState } from 'react';

const UserList = ({ users = [] }) => {


const [shownUsers, setShownUsers] = useState(users);

const hideUser = (userID) => {


const newUsers = users.filter(user => user.id === userID);
setShownUsers(newUsers);
};

return (
<div>
{userList.map(user => (
<div key={user.id}>
<h2> {user.name} </h2>
<button onClick={() => hideUser(user.id)}> hide user </button>
</div>
))}
</div>
)
}

const App = () => {


const users = [
{id: 1, name: 'Mike'},
{id: 2, name: 'Steve'},
{id: 3, name: 'Andrew'},

React Cheatsheet 21
{id: 4, name: 'Pierre'}

];

return <UserList users={users} />


}

In the UserList component, we receive a users array as a prop. We create a hideUser


function that filters out the selected user. However, every time we set shownUsers and re-
render the component, we recreate the hideUser function even though we don’t need to.
This recreation costs us performance.
We can wrap it in the useCallback hook which prevents our functions from being recreated
during re-renders.

import { useState, useCallback } from 'react';

const UserList = ({ users = [] }) => {


const [shownUsers, setShownUsers] = useState(users);

const hideUser = useCallback((userID) => {


const newUsers = users.filter(user => user.id === userID);
setShownUsers(newUsers);
}, [users]);

return (
<div>
{userList.map(user => (
<div key={user.id}>
<h2> {user.name} </h2>
<button onClick={() => hideUser(user.id)}> hide user </button>
</div>
))}
</div>
)
}

const App = () => {


const users = [
{id: 1, name: 'Mike'},
{id: 2, name: 'Steve'},
{id: 3, name: 'Andrew'},
{id: 4, name: 'Pierre'}

];

return <UserList users={users} />


}

React Cheatsheet 22
Now the hideUser function will only recreate if the users prop changes.

useMemo
The useMemo is a performance improvement hook that memoizes the return value of
a function.
Memoization is the caching of computed results from a expensive function call and
returning the cached result when the function is called with the same inputs.

It follows the same signature as useCallback taking two arguments:

1. The function we want memoize.

2. A dependency array containing values that the function uses. When any of these
values change it tells useMemo to rerun the function (with the new values) and
memoize the new return value.

import { useMemo } from 'react'

const MyComponent = () => {


const computedValue = useMemo(
() => { //...computationally expensive function },
[//dependencies]
)
}

Lets look at an example

import { useState } from 'react';

const factorialOf = (num) => {


if (num < 0)
return -1;
else if (num === 0)
return 1;
else {
return (num * factorialOf(num - 1));
}
}

const Factorial = () => {


const [number, setNumber] = useState(0);
const [bool, setBool] = useState(true);

const clickHandler = () => setBool(!bool);

React Cheatsheet 23
const factorialNumber = factorialOf(number); // Computationally expensive

return (
<div>
<input type='text' onChange={(event) => setNumber(event.target.value)} />
<h2>{ factorialNumber }</h2>
<button onClick={clickHandler}> re-render </button>
</div>
)
}

In this example, the factorialOf function is an expensive function to calculate. The


clickHandler function on the button click only serves to re-render our component by

calling a state setter function. Every time we render/re-render the component,


factorialNumber is recalculated, even when number hasn’t changed. It’s expensive to

recalculate factorialNumber needlessly whenever the component re-renders (it’s parent re-
renders or state changes unrelated to number i.e. setBool is called). We can fix this with
useMemo

import { useState, useMemo } from 'react';

const factorialOf = (num) => {


if (num < 0)
return -1;
else if (num === 0)
return 1;
else {
return (num * factorialOf(num - 1));
}
}

const Factorial = () => {


const [number, setNumber] = useState(0);
const [bool, setBool] = useState(true);

const clickHandler = () => setBool(!bool);

const factorialNumber = useMemo(factorialOf(number), [number]); // Computationally expensive

return (
<div>
<input type='text' onChange={(event) => setNumber(event.target.value)} />
<h2>{ factorialNumber }</h2>
<button onClick={clickHandler}> re-render </button>
</div>
)
}

React Cheatsheet 24
Here, factorialNumber will compute the value from factorialOf once per input of number
and cache it. Any future calls of factorialOf with the same number will return the cached
value saving us expensive and needless re-computations.

useContext
useContext allows us to access Context without need to use it’s Consumer component.
Without useContext

import { createContext } from 'react';

const TextContext = createContext('');

const ChildA = () => {


return (
<div>
<TextContext.Consumer>
{text => <p> {text} </p>}
</TextContext.Consumer>
</div>
)
}

const ParentA = () => {


return (
<div>
<h1> Parent A </h1>
<ChildA />
</div>
)
}

const App = () => {


return (
<TextContext.Provider value="Hello World">
<ParentA />
</TextContext.Provider>
)
}

To use the useContext hook, we pass it the context value we want to access.

import { createContext, useContext } from 'react';

const TextContext = createContext('');

React Cheatsheet 25
const ChildA = () => {
const text = useContext(TextContext);

return (
<div>
<p> {text} </p>
</div>
)
}

const ParentA = () => {


return (
<div>
<h1> Parent A </h1>
<ChildA />
</div>
)
}

const App = () => {


return (
<TextContext.Provider value="Hello World">
<ParentA />
</TextContext.Provider>
)
}

Class Component
Class components are the other type of component we can write. The common practice is
to use functional components but there are some existing use cases that still call for class
components. The JSX for the component is returned from the render method.

import { Component } from 'react';

class MyClassComponent extends Component {


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

React Cheatsheet 26
constructor
The constructor method runs before the class component mounts.

Typically used to declare the initial state and bind custom class methods to the class
instance.

import { Component } from 'react';

class Counter extends Component {


constructor(props) {
super(props);
this.state = { counter: 0 };
this.increment = this.increment.bind(this);
}

increment() {
// increment code
}
...
}

However, modern javascript syntax does not require a constructor . We can just use public
class fields.

class Counter extends Component {


state = { counter: 0 };

increment() {
// increment code
}
...
}

You access all methods, props and state of the class instance with the this keyword.

State
After initializing state in the component, the class instance has a setState method that
you must use if you wish to update the state. Do not mutate the state object!

setState(nextState, callback?)

You can pass setState two arguments, with the second being optional.

React Cheatsheet 27
1. The next state, either an object or a function.

a) With an object, just with the new fields you want updated. React will perform a shallow
merge of the new state object against the previous state object.

class Form extends Component {


state = {
name: '',
address: ''
};

handleNameChange = (e) => {


const newName = e.target.value;
this.setState({
name: newName
});
}

handleAddressChange = (e) => {


const newAddress = e.target.value;
this.setState({
address: newAddress
});
}

render() {
return (
<>
<input value={this.state.name} onChange={this.handleNameChange} />
<input value={this.state.address} onChange={this.handleAddressChange} />
<p>Hello, {this.state.name}. You live at {this.state.address} </p>
</>
);
}
}

b) With a pure function that receives the prevState and props. It should return the state
object to be shallowly merged with the previous state object.

class Counter extends Component {


state = {
count: 0,
};

increment = () => {
this.setState((prevState) => ({count: prevState.count + 1}))
}

React Cheatsheet 28
decrement = () => {
this.setState((prevState) => ({count: prevState.count - 1}))
}

render() {
return (
<>
<p> { this.state.count } </p>
<button onClick={this.increment}> Increment </button>
<button onClick={this.decrement}> Decrement </button>
</>
);
}
}

2. An optional callback that runs after the state is updated.

class Form extends Component {


state = {
name: '',
};

handleNameChange = (e) => {


const newName = e.target.value;
this.setState({
name: newName
}, () => { console.log('state updated!') });
}

render() {
return (
<>
<input value={this.state.name} onChange={this.handleNameChange} />
<p>Hello, {this.state.name} </p>
</>
);
}
}

Lifecycle Methods
Class components also have methods that hook into React’s rendering and re-rendering
cycles called lifecycle methods. Many methods are now deprecated or considered
UNSAFE as the React team is pushing forward with functional components + hooks. This
cheatsheet will only reference the commonly used ones.

React Cheatsheet 29
The full list can be found here

componentDidMount
The componentDidMount method calls after react mounts the component to the DOM.

import { Component } from 'react';

class UserList extends Component {


state = { users: [] }

componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => this.setState({users: users}
}

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

React Cheatsheet 30
componentWillUnmount
The componentWillUnmount method is called immediately before the component
unmounts. It is commonly used for cleanup.

import { Component } from 'react';

import { ChatAPI } from '../api/chatAPI';

class ChatWindow extends Component {


componentDidMount() {
ChatAPI.subscribeToUser(userID);
}

componentWillUnmount() {
ChatAPI.unsubscribeFromUser(userID);
}
render() {...}
}

componentDidUpdate
The componentDidUpdate method is called immediately after the component has re-
rendered from state or prop changes (ignoring the initial render).
A method that receives previous props and previous state which can be compared with
new state and props . This is often used to make network requests if needed. Take the
following example

import { Component } from 'react';

import { chatAPI } from '../api/chatAPI';

class ChatWindow extends Component {


state = {
serverURL: 'https://www.SomeChatServer.com'
};

componentDidMount() {
// open new subscription
chatAPI.subscribe(this.serverUrl, this.props.roomID);
}

React Cheatsheet 31
componentDidUpdate(prevProps, prevState) {
// Check if we've changed rooms or server
if (
this.props.roomID !== prevProps.roomID ||
this.state.serverUrl !== prevState.serverURL
) {
// unsubscribe from previous room and server
chatAPI.unsubscribe(prevState.serverURL, prevProps.roomID);
// subscribe to new room and server
chatAPI.subscribe(this.serverUrl, this.props.roomID);
}
}

componentWillUnmount() {
// close all subscriptions
chatAPI.unsubscribeAll();
}

// ...
}

Error Boundaries
getDerivedStateFromError
Error boundaries are components that catch errors that occur anywhere in their
child component tree. It allows us to display some fallback UI instead of the
component that crashed.
It is a class component we create that has a static getDerivedStateFromError method which
can update state in response to an error.
We wrap this error boundary component around the portion of our component tree we
want our fallback UI for. To set this up, we create state that tracks whether or not there is
an error. From the static getDerivedStateFromError method, we return the new state object
with the updated error state.

import React, { Component } from 'react';

class ErrorBoundary extends Component {


state = { hasError: false }

static getDerivedStateFromError(error) {
return { hasError: true };
}

React Cheatsheet 32
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>; // Fallback UI
}
return this.props.children;
}
}

const ChildComponent = () => {


throw new Error('Oops!'); // Error thrown
return <h1>Hello from child component</h1>;
}

const App = () => {


return (
<ErrorBoundary>
<ChildComponent />
</ErrorBoundary>
);
}

componentDidCatch
The componentDidCatch lifecycle method runs when a child component in its
component tree throws an error during rendering.
The method receives two parameters, the error that was thrown as well as info about
the rendering issue. It is commonly used in a Error Boundary component to log the error
to some error reporting service.

import React, { Component } from 'react';

import { errorService } from '../services/error-service'

class ErrorBoundary extends Component {


this.state = { hasError: false }

static getDerivedStateFromError(error) {
return { hasError: true };
}

componentDidCatch(error, info) {
errorService.log(error, info.componentStack);
}

render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>; // Fallback UI
}

React Cheatsheet 33
return this.props.children;
}
}

const ChildComponent = () => {


throw new Error('Oops!'); // Error thrown
return <h1>Hello from child component</h1>;
}

const App = () => {


return (
<ErrorBoundary>
<ChildComponent />
</ErrorBoundary>
);
}

Remember! getDerivedStateFromError is called during the render phase, so it does not


permit side effects such as logging errors. However, componentDidCatch is called during the
commit phase, where side effects are allowed such as logging our errors.

Useful Links
1. React Documentation

2. The Complete React Developer: Zero to Mastery

React Cheatsheet 34
React Interview Questions

To view the live version of the


page, click here.

© Copyright by Interviewbit
Contents

React Interview Questions for Freshers


1. What is React?
2. What are the advantages of using React?
3. What are the limitations of React?
4. What is useState() in React?
5. What are keys in React?
6. What is JSX?
7. What are the differences between functional and class components?
8. What is the virtual DOM? How does react use the virtual DOM to render the UI?
9. What are the differences between controlled and uncontrolled components?
10. What are props in React?
11. Explain React state and props.
12. Explain about types of side effects in React component.
13. What is prop drilling in React?
14. What are error boundaries?
15. What is React Hooks?
16. Explain React Hooks.
17. What are the rules that must be followed while using React Hooks?
18. What is the use of useEffect React Hooks?
19. Why do React Hooks make use of refs?
20. What are Custom Hooks?

Page 1 © Copyright by Interviewbit


React Interview Questions

React Interview Questions for Experienced


21. Explain Strict Mode in React.
22. How to prevent re-renders in React?
23. What are the different ways to style a React component?
24. Name a few techniques to optimize React app performance.
25. How to pass data between react components?
26. What are Higher Order Components?
27. What are the different phases of the component lifecycle?
28. What are the lifecycle methods of React?
29. Does React Hook work with static typing?
30. Explain about types of Hooks in React.
31. Differentiate React Hooks vs Classes.
32. How does the performance of using Hooks will differ in comparison with the
classes?
33. Do Hooks cover all the functionalities provided by the classes?
34. What is React Router?
35. Can React Hook replaces Redux?
36. Explain conditional rendering in React.
37. Explain how to create a simple React Hooks example program.
38. How to create a switching component for displaying different pages?
39. How to re-render the view when the browser is resized?
40. How to pass data between sibling components using React router?

Page 2 © Copyright by Interviewbit


React Interview Questions

React Interview Questions for Experienced


41. How to perform automatic redirect a er login?

Page 3 © Copyright by Interviewbit


Let's get Started

Introduction to React

React is an efficient, flexible, and open-source JavaScript framework library that


allows developers to the creation of simple, fast, and scalable web applications.
Jordan Walke, a so ware engineer who was working for Facebook created React. It
was first deployed on the news feed of Facebook in 2011 and on Instagram in 2012.
Developers from the Javascript background can easily develop web applications with
the help of React.
React Hooks will allow you to use the state and other features of React in which
requires a class to be written by you. In simple words, we can say that, React Hooks
are the functions that will connect React state with the lifecycle features from the
function components. React Hooks is among the features that are implemented
latest in the version React 16.8.
Scope of React: The selection of the right technology for application or web
development is becoming more challenging. React has been considered to be the
fastest-growing Javascript framework among all. The tools of Javascript are firming
their roots slowly and steadily in the marketplace and the React certification demand
is exponentially increasing. React is a clear win for front-end developers as it has a
quick learning curve, clean abstraction, and reusable components. Currently, there is
no end in sight for React as it keeps evolving.

React Interview Questions for Freshers


1. What is React?

Page 4 © Copyright by Interviewbit


React Interview Questions

React is a front-end and open-source JavaScript library which is useful in developing


user interfaces specifically for applications with a single page. It is helpful in building
complex and reusable user interface(UI) components of mobile and web applications
as it follows the component-based approach.
The important features of React are:
It supports server-side rendering.
It will make use of the virtual DOM rather than real DOM (Data Object Model) as
RealDOM manipulations are expensive.
It follows unidirectional data binding or data flow.
It uses reusable or composable UI components for developing the view.

2. What are the advantages of using React?


MVC is generally abbreviated as Model View Controller.
Use of Virtual DOM to improve efficiency: React uses virtual DOM to render the
view. As the name suggests, virtual DOM is a virtual representation of the real
DOM. Each time the data changes in a react app, a new virtual DOM gets created.
Creating a virtual DOM is much faster than rendering the UI inside the browser.
Therefore, with the use of virtual DOM, the efficiency of the app improves.
Gentle learning curve: React has a gentle learning curve when compared to
frameworks like Angular. Anyone with little knowledge of javascript can start
building web applications using React.
SEO friendly: React allows developers to develop engaging user interfaces that
can be easily navigated in various search engines. It also allows server-side
rendering, which boosts the SEO of an app.
Reusable components: React uses component-based architecture for
developing applications. Components are independent and reusable bits of
code. These components can be shared across various applications having
similar functionality. The re-use of components increases the pace of
development.
Huge ecosystem of libraries to choose from: React provides you with the
freedom to choose the tools, libraries, and architecture for developing an
application based on your requirement.

Page 5 © Copyright by Interviewbit


React Interview Questions

3. What are the limitations of React?


The few limitations of React are as given below:
React is not a full-blown framework as it is only a library.
The components of React are numerous and will take time to fully grasp the
benefits of all.
It might be difficult for beginner programmers to understand React.
Coding might become complex as it will make use of inline templating and JSX.

4. What is useState() in React?


The useState() is a built-in React Hook that allows you for having state variables in
functional components. It should be used when the DOM has something that is
dynamically manipulating/controlling.
In the below-given example code, The useState(0) will return a tuple where the count
is the first parameter that represents the counter’s current state and the second
parameter setCounter method will allow us to update the state of the counter.

...
const [count, setCounter] = useState(0);
const [otherStuffs, setOtherStuffs] = useState(...);
...
const setCount = () => {
setCounter(count + 1);
setOtherStuffs(...);
...
};

We can make use of setCounter() method for updating the state of count anywhere.
In this example, we are using setCounter() inside the setCount function where various
other things can also be done. The idea with the usage of hooks is that we will be able
to keep our code more functional and avoid class-based components if they are not
required.

5. What are keys in React?


A key is a special string attribute that needs to be included when using lists of
elements.

Page 6 © Copyright by Interviewbit


React Interview Questions

Example of a list using key -

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


const listElements = ids.map((id)=>{
return(
<li key={id.toString()}>
{id}
</li>
)
})

Importance of keys -
Keys help react identify which elements were added, changed or removed.
Keys should be given to array elements for providing a unique identity for each
element.
Without keys, React does not understand the order or uniqueness of each
element.
With keys, React has an idea of which particular element was deleted, edited,
and added.
Keys are generally used for displaying a list of data coming from an API.

Page 7 © Copyright by Interviewbit


React Interview Questions

***Note- Keys used within arrays should be unique among siblings. They need
not be globally unique.

6. What is JSX?
JSX stands for JavaScript XML. It allows us to write HTML inside JavaScript and place
them in the DOM without using functions like appendChild( ) or createElement( ).
As stated in the official docs of React, JSX provides syntactic sugar for
React.createElement( ) function.
Note- We can create react applications without using JSX as well.
Let’s understand how JSX works:
Without using JSX, we would have to create an element by the following process:

const text = React.createElement('p', {}, 'This is a text');


const container = React.createElement('div','{}',text );
ReactDOM.render(container,rootElement);

Using JSX, the above code can be simplified:

const container = (
<div>
<p>This is a text</p>
</div>
);
ReactDOM.render(container,rootElement);

As one can see in the code above, we are directly using HTML inside JavaScript.

7. What are the differences between functional and class


components?
Before the introduction of Hooks in React, functional components were called
stateless components and were behind class components on a feature basis. A er
the introduction of Hooks, functional components are equivalent to class
components.

Page 8 © Copyright by Interviewbit


React Interview Questions

Although functional components are the new trend, the react team insists on
keeping class components in React. Therefore, it is important to know how these
components differ.
On the following basis let’s compare functional and class components:
Declaration
Functional components are nothing but JavaScript functions and therefore can be
declared using an arrow function or the function keyword:

function card(props){
return(
<div className="main-container">
<h2>Title of the card</h2>
</div>
)
}
const card = (props) =>{
return(
<div className="main-container">
<h2>Title of the card</h2>
</div>
)
}

Class components, on the other hand, are declared using the ES6 class:

class Card extends React.Component{


constructor(props){
super(props);
}
render(){
return(
<div className="main-container">
<h2>Title of the card</h2>
</div>
)
}
}

Handling props

Page 9 © Copyright by Interviewbit


React Interview Questions

Let’s render the following component with props and analyse how functional and
class components handle props:

<Student Info name="Vivek" rollNumber="23" />

In functional components, the handling of props is pretty straightforward. Any prop


provided as an argument to a functional component can be directly used inside
HTML elements:

function StudentInfo(props){
return(
<div className="main">
<h2>{props.name}</h2>
<h4>{props.rollNumber}</h4>
</div>
)
}

In the case of class components, props are handled in a different way:

class StudentInfo extends React.Component{


constructor(props){
super(props);
}
render(){
return(
<div className="main">
<h2>{this.props.name}</h2>
<h4>{this.props.rollNumber}</h4>
</div>
)
}
}

As we can see in the code above, this keyword is used in the case of class
components.
Handling state
Functional components use React hooks to handle state. It uses the useState hook to
set the state of a variable inside the component:

Page 10 © Copyright by Interviewbit


React Interview Questions

function ClassRoom(props){
let [studentsCount,setStudentsCount] = useState(0);
const addStudent = () => {
setStudentsCount(++studentsCount);
}
return(
<div>
<p>Number of students in class room: {studentsCount}</p>
<button onClick={addStudent}>Add Student</button>
</div>
)
}

Since useState hook returns an array of two items, the first item contains the current
state, and the second item is a function used to update the state.
In the code above, using array destructuring we have set the variable name to
studentsCount with a current value of “0” and setStudentsCount is the function that
is used to update the state.
For reading the state, we can see from the code above, the variable name can be
directly used to read the current state of the variable.
We cannot use React Hooks inside class components, therefore state handling is
done very differently in a class component:
Let’s take the same above example and convert it into a class component:

Page 11 © Copyright by Interviewbit


React Interview Questions

class ClassRoom extends React.Component{


constructor(props){
super(props);
this.state = {studentsCount : 0};

this.addStudent = this.addStudent.bind(this);
}

addStudent(){
this.setState((prevState)=>{
return {studentsCount: prevState.studentsCount++}
});
}

render(){
return(
<div>
<p>Number of students in class room: {this.state.studentsCount}</p>
<button onClick={this.addStudent}>Add Student</button>
</div>
)
}
}

In the code above, we see we are using this.state to add the variable studentsCount
and setting the value to “0”.
For reading the state, we are using this.state.studentsCount.
For updating the state, we need to first bind the addStudent function to this. Only
then, we will be able to use the setState function which is used to update the state.

8. What is the virtual DOM? How does react use the virtual DOM
to render the UI?
As stated by the react team, virtual DOM is a concept where a virtual representation
of the real DOM is kept inside the memory and is synced with the real DOM by a
library such as ReactDOM.

Page 12 © Copyright by Interviewbit


React Interview Questions

Why was virtual DOM introduced?


DOM manipulation is an integral part of any web application, but DOM manipulation
is quite slow when compared to other operations in JavaScript. The efficiency of the
application gets affected when several DOM manipulations are being done. Most
JavaScript frameworks update the entire DOM even when a small part of the DOM
changes.
For example, consider a list that is being rendered inside the DOM. If one of the items
in the list changes, the entire list gets rendered again instead of just rendering the
item that was changed/updated. This is called inefficient updating.
To address the problem of inefficient updating, the react team introduced the
concept of virtual DOM.
How does it work?

Page 13 © Copyright by Interviewbit


React Interview Questions

For every DOM object, there is a corresponding virtual DOM object(copy), which has
the same properties. The main difference between the real DOM object and the
virtual DOM object is that any changes in the virtual DOM object will not reflect on the
screen directly. Consider a virtual DOM object as a blueprint of the real DOM object.
Whenever a JSX element gets rendered, every virtual DOM object gets updated.
**Note- One may think updating every virtual DOM object might be inefficient,
but that’s not the case. Updating the virtual DOM is much faster than updating
the real DOM since we are just updating the blueprint of the real DOM.
React uses two virtual DOMs to render the user interface. One of them is used to store
the current state of the objects and the other to store the previous state of the
objects. Whenever the virtual DOM gets updated, react compares the two virtual
DOMs and gets to know about which virtual DOM objects were updated. A er
knowing which objects were updated, react renders only those objects inside the real
DOM instead of rendering the complete real DOM. This way, with the use of virtual
DOM, react solves the problem of inefficient updating.

9. What are the differences between controlled and


uncontrolled components?
Controlled and uncontrolled components are just different approaches to handling
input from elements in react.

Page 14 © Copyright by Interviewbit


React Interview Questions

Feature Uncontrolled Controlled Name attrs

One-time
value
retrieval ✔ ✔ ✔
(e.g. on
submit)

Validating on
✔ ✔ ✔
submit

Field-level
❌ ✔ ✔
Validation

Conditionally
disabling
❌ ✔ ✔
submit
button

Enforcing
❌ ✔ ✔
input format

several
inputs for
❌ ✔ ✔
one piece of
data

dynamic
❌ ✔
inputs

Page 15 © Copyright by Interviewbit


React Interview Questions

Controlled component: In a controlled component, the value of the input


element is controlled by React. We store the state of the input element inside
the code, and by using event-based callbacks, any changes made to the input
element will be reflected in the code as well.
When a user enters data inside the input element of a controlled component,
onChange function gets triggered and inside the code, we check whether the value
entered is valid or invalid. If the value is valid, we change the state and re-render the
input element with the new value.
Example of a controlled component:

function FormValidation(props) {
let [inputValue, setInputValue] = useState("");
let updateInput = e => {
setInputValue(e.target.value);
};
return (
<div>
<form>
<input type="text" value={inputValue} onChange={updateInput} />
</form>
</div>
);
}

As one can see in the code above, the value of the input element is determined by the
state of the inputValue variable. Any changes made to the input element is handled
by the updateInput function.
Uncontrolled component: In an uncontrolled component, the value of the input
element is handled by the DOM itself. Input elements inside uncontrolled
components work just like normal HTML input form elements.
The state of the input element is handled by the DOM. Whenever the value of the
input element is changed, event-based callbacks are not called. Basically, react does
not perform any action when there are changes made to the input element.
Whenever use enters data inside the input field, the updated data is shown directly.
To access the value of the input element, we can use ref.

Page 16 © Copyright by Interviewbit


React Interview Questions

Example of an uncontrolled component:

function FormValidation(props) {
let inputValue = React.createRef();
let handleSubmit = e => {
alert(`Input value: ${inputValue.current.value}`);
e.preventDefault();
};
return (
<div>
<form onSubmit={handleSubmit}>
<input type="text" ref={inputValue} />
<button type="submit">Submit</button>
</form>
</div>
);
}

As one can see in the code above, we are not using onChange function to govern the
changes made to the input element. Instead, we are using ref to access the value of
the input element.

10. What are props in React?


The props in React are the inputs to a component of React. They can be single-valued
or objects having a set of values that will be passed to components of React during
creation by using a naming convention that almost looks similar to HTML-tag
attributes. We can say that props are the data passed from a parent component into
a child component.
The main purpose of props is to provide different component functionalities such as:
Passing custom data to the React component.
Using through this.props.reactProp inside render() method of the component.
Triggering state changes.
For example, consider we are creating an element with reactProp property as given
below: <Element reactProp = "1" />
This reactProp name will be considered as a property attached to the native props
object of React which already exists on each component created with the help of
React library: props.reactProp; .

Page 17 © Copyright by Interviewbit


React Interview Questions

11. Explain React state and props.

Props State

Immutable Owned by its component

Has better performance Locally scoped

Can be passed to child


Writeable/Mutable
components

has setState() method to modify


properties

Changes to state can be


asynchronous

can only be passed as props

React State
Every component in react has a built-in state object, which contains all the
property values that belong to that component.
In other words, the state object controls the behaviour of a component. Any
change in the property values of the state object leads to the re-rendering of the
component.
Note- State object is not available in functional components but, we can use
React Hooks to add state to a functional component.
How to declare a state object?
Example:

Page 18 © Copyright by Interviewbit


React Interview Questions

class Car extends React.Component{


constructor(props){
super(props);
this.state = {
brand: "BMW",
color: "black"
}
}
}

How to use and update the state object?

class Car extends React.Component {


constructor(props) {
super(props);
this.state = {
brand: "BMW",
color: "Black"
};
}
changeColor() {
this.setState(prevState => {
return { color: "Red" };
});
}
render() {
return (
<div>
<button onClick={() => this.changeColor()}>Change Color</button>
<p>{this.state.color}</p>
</div>
);
}
}

As one can see in the code above, we can use the state by calling
this.state.propertyName and we can change the state object property using
setState method.
React Props
Every React component accepts a single object argument called props (which stands
for “properties”). These props can be passed to a component using HTML attributes
and the component accepts these props as an argument.

Page 19 © Copyright by Interviewbit


React Interview Questions

Using props, we can pass data from one component to another.


Passing props to a component:
While rendering a component, we can pass the props as an HTML attribute:

<Car brand="Mercedes"/>

The component receives the props:


In Class component:

class Car extends React.Component {


constructor(props) {
super(props);
this.state = {
brand: this.props.brand,
color: "Black"
};
}
}

In Functional component:

function Car(props) {
let [brand, setBrand] = useState(props.brand);
}

Note- Props are read-only. They cannot be manipulated or changed inside a


component.

12. Explain about types of side effects in React component.


There are two types of side effects in React component. They are:

Page 20 © Copyright by Interviewbit


React Interview Questions

Effects without Cleanup: This side effect will be used in useEffect which does
not restrict the browser from screen update. It also improves the responsiveness
of an application. A few common examples are network requests, Logging,
manual DOM mutations, etc.
Effects with Cleanup: Some of the Hook effects will require the cleanup a er
updating of DOM is done. For example, if you want to set up an external data
source subscription, it requires cleaning up the memory else there might be a
problem of memory leak. It is a known fact that React will carry out the cleanup
of memory when the unmounting of components happens. But the effects will
run for each render() method rather than for any specific method. Thus we can
say that, before execution of the effects succeeding time the React will also
cleanup effects from the preceding render.

13. What is prop drilling in React?

Sometimes while developing React applications, there is a need to pass data from a
component that is higher in the hierarchy to a component that is deeply nested. To
pass data between such components, we pass props from a source component and
keep passing the prop to the next component in the hierarchy till we reach the
deeply nested component.
The disadvantage of using prop drilling is that the components that should
otherwise be not aware of the data have access to the data.

14. What are error boundaries?

Page 21 © Copyright by Interviewbit


React Interview Questions

Introduced in version 16 of React, Error boundaries provide a way for us to catch


errors that occur in the render phase.
What is an error boundary?
Any component which uses one of the following lifecycle methods is considered an
error boundary.
In what places can an error boundary detect an error?
1. Render phase
2. Inside a lifecycle method
3. Inside the constructor
Without using error boundaries:

class CounterComponent extends React.Component{


constructor(props){
super(props);
this.state = {
counterValue: 0
}
this.incrementCounter = this.incrementCounter.bind(this);
}
incrementCounter(){
this.setState(prevState => counterValue = prevState+1);
}
render(){
if(this.state.counter === 2){
throw new Error('Crashed');
}
return(
<div>
<button onClick={this.incrementCounter}>Increment Value</button>
<p>Value of counter: {this.state.counterValue}</p>
</div>
)
}
}

In the code above, when the counterValue equals 2, we throw an error inside the
render method.

Page 22 © Copyright by Interviewbit


React Interview Questions

When we are not using the error boundary, instead of seeing an error, we see a blank
page. Since any error inside the render method leads to unmounting of the
component. To display an error that occurs inside the render method, we use error
boundaries.
With error boundaries: As mentioned above, error boundary is a component using
one or both of the following methods: static getDerivedStateFromError and
componentDidCatch.
Let’s create an error boundary to handle errors in the render phase:

class ErrorBoundary extends React.Component {


constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
logErrorToMyService(error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h4>Something went wrong</h4>
}
return this.props.children;
}
}

In the code above, getDerivedStateFromError function renders the fallback UI


interface when the render method has an error.
componentDidCatch logs the error information to an error tracking service.
Now with the error boundary, we can render the CounterComponent in the following
way:

<ErrorBoundary>
<CounterComponent/>
</ErrorBoundary>

Page 23 © Copyright by Interviewbit


React Interview Questions

15. What is React Hooks?


React Hooks are the built-in functions that permit developers for using the state and
lifecycle methods within React components. These are newly added features made
available in React 16.8 version. Each lifecycle of a component is having 3 phases
which include mount, unmount, and update. Along with that, components have
properties and states. Hooks will allow using these methods by developers for
improving the reuse of code with higher flexibility navigating the component tree.
Using Hook, all features of React can be used without writing class components. For
example, before React version 16.8, it required a class component for managing the
state of a component. But now using the useState hook, we can keep the state in a
functional component.

16. Explain React Hooks.


What are Hooks? Hooks are functions that let us “hook into” React state and
lifecycle features from a functional component.
React Hooks cannot be used in class components. They let us write components
without class.
Why were Hooks introduced in React?
React hooks were introduced in the 16.8 version of React. Previously, functional
components were called stateless components. Only class components were used for
state management and lifecycle methods. The need to change a functional
component to a class component, whenever state management or lifecycle methods
were to be used, led to the development of Hooks.
Example of a hook: useState hook:
In functional components, the useState hook lets us define a state for a component:

function Person(props) {
// We are declaring a state variable called name.
// setName is a function to update/change the value of name
let [name, setName] = useState('');
}

Page 24 © Copyright by Interviewbit


React Interview Questions

The state variable “name” can be directly used inside the HTML.

17. What are the rules that must be followed while using React
Hooks?
There are 2 rules which must be followed while you code with Hooks:
React Hooks must be called only at the top level. It is not allowed to call them
inside the nested functions, loops, or conditions.
It is allowed to call the Hooks only from the React Function Components.

18. What is the use of useEffect React Hooks?


The useEffect React Hook is used for performing the side effects in functional
components. With the help of useEffect, you will inform React that your component
requires something to be done a er rendering the component or a er a state
change. The function you have passed(can be referred to as “effect”) will be
remembered by React and call a erwards the performance of DOM updates is over.
Using this, we can perform various calculations such as data fetching, setting up
document title, manipulating DOM directly, etc, that don’t target the output value.
The useEffect hook will run by default a er the first render and also a er each update
of the component. React will guarantee that the DOM will be updated by the time
when the effect has run by it.
The useEffect React Hook will accept 2 arguments: useEffect(callback[,
dependencies]);

Where the first argument callback represents the function having the logic of side-
effect and it will be immediately executed a er changes were being pushed to DOM.
The second argument dependencies represent an optional array of dependencies.
The useEffect() will execute the callback only if there is a change in dependencies in
between renderings.
Example:

Page 25 © Copyright by Interviewbit


React Interview Questions

import { useEffect } from 'react';


function WelcomeGreetings({ name }) {
const msg = `Hi, ${name}!`; // Calculates output
useEffect(() => {
document.title = `Welcome to you ${name}`; // Side-effect!
}, [name]);
return <div>{msg}</div>; // Calculates output
}

The above code will update the document title which is considered to be a side-effect
as it will not calculate the component output directly. That is why updating of
document title has been placed in a callback and provided to useEffect().
Consider you don’t want to execute document title update each time on rendering of
WelcomeGreetings component and you want it to be executed only when the name
prop changes then you need to supply name as a dependency to useEffect(callback,
[name]) .

19. Why do React Hooks make use of refs?


Earlier, refs were only limited to class components but now it can also be accessible
in function components through the useRef Hook in React.
The refs are used for:
Managing focus, media playback, or text selection.
Integrating with DOM libraries by third-party.
Triggering the imperative animations.

20. What are Custom Hooks?


A Custom Hook is a function in Javascript whose name begins with ‘use’ and which
calls other hooks. It is a part of React v16.8 hook update and permits you for reusing
the stateful logic without any need for component hierarchy restructuring.
In almost all of the cases, custom hooks are considered to be sufficient for replacing
render props and HoCs (Higher-Order components) and reducing the amount of
nesting required. Custom Hooks will allow you for avoiding multiple layers of
abstraction or wrapper hell that might come along with Render Props and HoCs.

Page 26 © Copyright by Interviewbit


React Interview Questions

The disadvantage of Custom Hooks is it cannot be used inside of the classes.

React Interview Questions for Experienced


21. Explain Strict Mode in React.
StrictMode is a tool added in version 16.3 of React to highlight potential problems in
an application. It performs additional checks on the application.

function App() {
return (
<React.StrictMode>
<div classname="App">
<Header/>
<div>
Page Content
</div>
<Footer/>
</div>
</React.StrictMode>
);
}

To enable StrictMode, <React.StrictMode> tags need to be added inside the


application:

import React from "react";


import ReactDOM from "react-dom";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
rootElement
);

StrictMode currently helps with the following issues:

Page 27 © Copyright by Interviewbit


React Interview Questions

Identifying components with unsafe lifecycle methods:


Certain lifecycle methods are unsafe to use in asynchronous react
applications. With the use of third-party libraries, it becomes difficult to
ensure that certain lifecycle methods are not used.
StrictMode helps in providing us with a warning if any of the class
components use an unsafe lifecycle method.
Warning about the usage of legacy string API:
If one is using an older version of React, callback ref is the recommended
way to manage refs instead of using the string refs. StrictMode gives a
warning if we are using string refs to manage refs.
Warning about the usage of findDOMNode:
Previously, findDOMNode( ) method was used to search the tree of a DOM
node. This method is deprecated in React. Hence, the StrictMode gives us a
warning about the usage of this method.
Warning about the usage of legacy context API (because the API is error-
prone).

22. How to prevent re-renders in React?


Reason for re-renders in React:
Re-rendering of a component and its child components occur when props
or the state of the component has been changed.
Re-rendering components that are not updated, affects the performance of
an application.
How to prevent re-rendering:
Consider the following components:

Page 28 © Copyright by Interviewbit


React Interview Questions

class Parent extends React.Component {


state = { messageDisplayed: false };
componentDidMount() {
this.setState({ messageDisplayed: true });
}
render() {
console.log("Parent is getting rendered");
return (
<div className="App">
<Message />
</div>
);
}
}
class Message extends React.Component {
constructor(props) {
super(props);
this.state = { message: "Hello, this is vivek" };
}
render() {
console.log("Message is getting rendered");
return (
<div>
<p>{this.state.message}</p>
</div>
);
}
}

The Parent component is the parent component and the Message is the child
component. Any change in the parent component will lead to re-rendering of
the child component as well. To prevent the re-rendering of child components,
we use the shouldComponentUpdate( ) method:
**Note- Use shouldComponentUpdate( ) method only when you are sure that it’s
a static component.

Page 29 © Copyright by Interviewbit


React Interview Questions

class Message extends React.Component {


constructor(props) {
super(props);
this.state = { message: "Hello, this is vivek" };
}
shouldComponentUpdate() {
console.log("Does not get rendered");
return false;
}
render() {
console.log("Message is getting rendered");
return (
<div>
<p>{this.state.message}</p>
</div>
);
}
}

As one can see in the code above, we have returned false from the
shouldComponentUpdate( ) method, which prevents the child component from re-
rendering.

23. What are the different ways to style a React component?


There are many different ways through which one can style a React component.
Some of the ways are :
Inline Styling: We can directly style an element using inline style attributes.
Make sure the value of style is a JavaScript object:

class RandomComponent extends React.Component {


render() {
return (
<div>
<h3 style={{ color: "Yellow" }}>This is a heading</h3>
<p style={{ fontSize: "32px" }}>This is a paragraph</p>
</div>
);
}
}

Page 30 © Copyright by Interviewbit


React Interview Questions

Using JavaScript object: We can create a separate JavaScript object and set the
desired style properties. This object can be used as the value of the inline style
attribute.

class RandomComponent extends React.Component {


paragraphStyles = {
color: "Red",
fontSize: "32px"
};

headingStyles = {
color: "blue",
fontSize: "48px"
};

render() {
return (
<div>
<h3 style={this.headingStyles}>This is a heading</h3>
<p style={this.paragraphStyles}>This is a paragraph</p>
</div>
);
}
}

CSS Stylesheet: We can create a separate CSS file and write all the styles for the
component inside that file. This file needs to be imported inside the component
file.

import './RandomComponent.css';

class RandomComponent extends React.Component {


render() {
return (
<div>
<h3 className="heading">This is a heading</h3>
<p className="paragraph">This is a paragraph</p>
</div>
);
}
}

Page 31 © Copyright by Interviewbit


React Interview Questions

CSS Modules: We can create a separate CSS module and import this module
inside our component. Create a file with “.module.css”‘ extension,
styles.module.css:

.paragraph{
color:"red";
border:1px solid black;
}

We can import this file inside the component and use it:

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

class RandomComponent extends React.Component {


render() {
return (
<div>
<h3 className="heading">This is a heading</h3>
<p className={styles.paragraph} >This is a paragraph</p>
</div>
);
}
}

24. Name a few techniques to optimize React app performance.


There are many ways through which one can optimize the performance of a React
app, let’s have a look at some of them:

Page 32 © Copyright by Interviewbit


React Interview Questions

Using useMemo( ) -
It is a React hook that is used for caching CPU-Expensive functions.
Sometimes in a React app, a CPU-Expensive function gets called repeatedly
due to re-renders of a component, which can lead to slow rendering.
useMemo( ) hook can be used to cache such functions. By using useMemo(
), the CPU-Expensive function gets called only when it is needed.
Using React.PureComponent -
It is a base component class that checks the state and props of a
component to know whether the component should be updated.
Instead of using the simple React.Component, we can use
React.PureComponent to reduce the re-renders of a component
unnecessarily.
Maintaining State Colocation -
This is a process of moving the state as close to where you need it as
possible.
Sometimes in React app, we have a lot of unnecessary states inside the
parent component which makes the code less readable and harder to
maintain. Not to forget, having many states inside a single component
leads to unnecessary re-renders for the component.
It is better to shi states which are less valuable to the parent component,
to a separate component.
Lazy Loading -
It is a technique used to reduce the load time of a React app. Lazy loading
helps reduce the risk of web app performances to a minimum.

25. How to pass data between react components?

Page 33 © Copyright by Interviewbit


React Interview Questions

Parent Component to Child Component (using props)


With the help of props, we can send data from a parent to a child component.
How do we do this?
Consider the following Parent Component:

import ChildComponent from "./Child";


function ParentComponent(props) {
let [counter, setCounter] = useState(0);

let increment = () => setCounter(++counter);

return (
<div>
<button onClick={increment}>Increment Counter</button>
<ChildComponent counterValue={counter} />
</div>
);
}

As one can see in the code above, we are rendering the child component inside the
parent component, by providing a prop called counterValue. The value of the counter
is being passed from the parent to the child component.
We can use the data passed by the parent component in the following way:

Page 34 © Copyright by Interviewbit


React Interview Questions

function ChildComponent(props) {
return (
<div>
<p>Value of counter: {props.counterValue}</p>
</div>
);
}

We use the props.counterValue to display the data passed on by the parent


component.
Child Component to Parent Component (using callbacks)
This one is a bit tricky. We follow the steps below:
Create a callback in the parent component which takes in the data needed as a
parameter.
Pass this callback as a prop to the child component.
Send data from the child component using the callback.
We are considering the same example above but in this case, we are going to pass the
updated counterValue from child to parent.
Step1 and Step2: Create a callback in the parent component, pass this callback as a
prop.

function ParentComponent(props) {
let [counter, setCounter] = useState(0);
let callback = valueFromChild => setCounter(valueFromChild);
return (
<div>
<p>Value of counter: {counter}</p>
<ChildComponent callbackFunc={callback} counterValue={counter} />
</div>
);
}

As one can see in the code above, we created a function called callback which takes
in the data received from the child component as a parameter.
Next, we passed the function callback as a prop to the child component.

Page 35 © Copyright by Interviewbit


React Interview Questions

Step3: Pass data from the child to the parent component.

function ChildComponent(props) {
let childCounterValue = props.counterValue;
return (
<div>
<button onClick={() => props.callbackFunc(++childCounterValue)}>
Increment Counter
</button>
</div>
);
}

In the code above, we have used the props.counterValue and set it to a variable called
childCounterValue.
Next, on button click, we pass the incremented childCounterValue to the
props.callbackFunc.
This way, we can pass data from the child to the parent component.

26. What are Higher Order Components?


Simply put, Higher-Order Component(HOC) is a function that takes in a component
and returns a new component.

When do we need a Higher Order Component?

Page 36 © Copyright by Interviewbit


React Interview Questions

While developing React applications, we might develop components that are quite
similar to each other with minute differences. In most cases, developing similar
components might not be an issue but, while developing larger applications we need
to keep our code DRY, therefore, we want an abstraction that allows us to define this
logic in a single place and share it across components. HOC allows us to create that
abstraction.
Example of a HOC:
Consider the following components having similar functionality. The following
component displays the list of articles:

Page 37 © Copyright by Interviewbit


React Interview Questions

// "GlobalDataSource" is some global data source


class ArticlesList extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
articles: GlobalDataSource.getArticles(),
};
}
componentDidMount() {
// Listens to the changes added
GlobalDataSource.addChangeListener(this.handleChange);
}
componentWillUnmount() {
// Listens to the changes removed
GlobalDataSource.removeChangeListener(this.handleChange);
}
handleChange() {
// States gets Update whenver data source changes
this.setState({
articles: GlobalDataSource.getArticles(),
});
}
render() {
return (
<div>
{this.state.articles.map((article) => (
<ArticleData article={article} key={article.id} />
))}
</div>
);
}
}

The following component displays the list of users:

Page 38 © Copyright by Interviewbit


React Interview Questions

// "GlobalDataSource" is some global data source


class UsersList extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
users: GlobalDataSource.getUsers(),
};
}
componentDidMount() {
// Listens to the changes added
GlobalDataSource.addChangeListener(this.handleChange);
}
componentWillUnmount() {
// Listens to the changes removed
GlobalDataSource.removeChangeListener(this.handleChange);
}
handleChange() {
// States gets Update whenver data source changes
this.setState({
users: GlobalDataSource.getUsers(),
});
}
render() {
return (
<div>
{this.state.users.map((user) => (
<UserData user={user} key={user.id} />
))}
</div>
);
}
}

Notice the above components, both have similar functionality but, they are calling
different methods to an API endpoint.
Let’s create a Higher Order Component to create an abstraction:

Page 39 © Copyright by Interviewbit


React Interview Questions

// Higher Order Component which takes a component


// as input and returns another component
// "GlobalDataSource" is some global data source
function HOC(WrappedComponent, selectData) {
return class extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
data: selectData(GlobalDataSource, props),
};
}
componentDidMount() {
// Listens to the changes added
GlobalDataSource.addChangeListener(this.handleChange);
}
componentWillUnmount() {
// Listens to the changes removed
GlobalDataSource.removeChangeListener(this.handleChange);
}
handleChange() {
this.setState({
data: selectData(GlobalDataSource, this.props),
});
}
render() {
// Rendering the wrapped component with the latest data data
return <WrappedComponent data={this.state.data} {...this.props} />;
}
};
}

We know HOC is a function that takes in a component and returns a component.


In the code above, we have created a function called HOC which returns a component
and performs functionality that can be shared across both the ArticlesList
component and UsersList Component.
The second parameter in the HOC function is the function that calls the method on
the API endpoint.
We have reduced the duplicated code of the componentDidUpdate and
componentDidMount functions.

Page 40 © Copyright by Interviewbit


React Interview Questions

Using the concept of Higher-Order Components, we can now render the ArticlesList
and UsersList components in the following way:

const ArticlesListWithHOC = HOC(ArticlesList, (GlobalDataSource) => GlobalDataSource.ge


const UsersListWithHOC = HOC(UsersList, (GlobalDataSource) => GlobalDataSource.getUsers

Remember, we are not trying to change the functionality of each component, we are
trying to share a single functionality across multiple components using HOC.

27. What are the different phases of the component lifecycle?


There are four different phases in the lifecycle of React component. They are:
Initialization: During this phase, React component will prepare by setting up
the default props and initial state for the upcoming tough journey.
Mounting: Mounting refers to putting the elements into the browser DOM. Since
React uses VirtualDOM, the entire browser DOM which has been currently
rendered would not be refreshed. This phase includes the lifecycle methods
componentWillMount and componentDidMount .
Updating: In this phase, a component will be updated when there is a change in
the state or props of a component. This phase will have lifecycle methods like
componentWillUpdate , shouldComponentUpdate , render , and
componentDidUpdate .
Unmounting: In this last phase of the component lifecycle, the component will
be removed from the DOM or will be unmounted from the browser DOM. This
phase will have the lifecycle method named componentWillUnmount .

Page 41 © Copyright by Interviewbit


React Interview Questions

28. What are the lifecycle methods of React?


React lifecycle hooks will have the methods that will be automatically called at
different phases in the component lifecycle and thus it provides good control over
what happens at the invoked point. It provides the power to effectively control and
manipulate what goes on throughout the component lifecycle.
For example, if you are developing the YouTube application, then the application will
make use of a network for buffering the videos and it consumes the power of the
battery (assume only these two). A er playing the video if the user switches to any
other application, then you should make sure that the resources like network and
battery are being used most efficiently. You can stop or pause the video buffering
which in turn stops the battery and network usage when the user switches to another
application a er video play.
So we can say that the developer will be able to produce a quality application with
the help of lifecycle methods and it also helps developers to make sure to plan what
and how to do it at different points of birth, growth, or death of user interfaces.
The various lifecycle methods are:

Page 42 © Copyright by Interviewbit


React Interview Questions

constructor(): This method will be called when the component is initiated


before anything has been done. It helps to set up the initial state and initial
values.
getDerivedStateFromProps() : This method will be called just before element(s)
rendering in the DOM. It helps to set up the state object depending on the initial
props. The getDerivedStateFromProps() method will have a state as an
argument and it returns an object that made changes to the state. This will be
the first method to be called on an updating of a component.
render() : This method will output or re-render the HTML to the DOM with
new changes. The render() method is an essential method and will be called
always while the remaining methods are optional and will be called only if they
are defined.
componentDidMount() : This method will be called a er the rendering of the
component. Using this method, you can run statements that need the
component to be already kept in the DOM.
shouldComponentUpdate() : The Boolean value will be returned by this method
which will specify whether React should proceed further with the rendering or
not. The default value for this method will be True.
getSnapshotBeforeUpdate() : This method will provide access for the props as
well as for the state before the update. It is possible to check the previously
present value before the update, even a er the update.
componentDidUpdate() : This method will be called a er the component has
been updated in the DOM.
componentWillUnmount() : This method will be called when the component
removal from the DOM is about to happen.

29. Does React Hook work with static typing?


Static typing refers to the process of code check during the time of compilation for
ensuring all variables will be statically typed. React Hooks are functions that are
designed to make sure about all attributes must be statically typed. For enforcing
stricter static typing within our code, we can make use of the React API with custom
Hooks.

Page 43 © Copyright by Interviewbit


React Interview Questions

30. Explain about types of Hooks in React.


There are two types of Hooks in React. They are:
1. Built-in Hooks: The built-in Hooks are divided into 2 parts as given below:
Basic Hooks:
useState() : This functional component is used to set and retrieve the
state.
useEffect() : It enables for performing the side effects in the functional
components.
useContext() : It is used for creating common data that is to be accessed
by the components hierarchy without having to pass the props down to
each level.
Additional Hooks:
useReducer() : It is used when there is a complex state logic that is having
several sub-values or when the upcoming state is dependent on the
previous state. It will also enable you to optimization of component
performance that will trigger deeper updates as it is permitted to pass the
dispatch down instead of callbacks.
useMemo() : This will be used for recomputing the memoized value when
there is a change in one of the dependencies. This optimization will help for
avoiding expensive calculations on each render.
useCallback() : This is useful while passing callbacks into the optimized
child components and depends on the equality of reference for the
prevention of unneeded renders.
useImperativeHandle() : It will enable modifying the instance that will be
passed with the ref object.
useDebugValue() : It is used for displaying a label for custom hooks in React
DevTools.
useRef() : It will permit creating a reference to the DOM element directly
within the functional component.
useLayoutEffect() : It is used for the reading layout from the DOM and re-
rendering synchronously.

Page 44 © Copyright by Interviewbit


React Interview Questions

2. Custom Hooks: A custom Hook is basically a function of JavaScript. The Custom


Hook working is similar to a regular function. The “use” at the beginning of the
Custom Hook Name is required for React to understand that this is a custom Hook
and also it will describe that this specific function follows the rules of Hooks.
Moreover, developing custom Hooks will enable you for extracting component logic
from within reusable functions.

31. Differentiate React Hooks vs Classes.

Page 45 © Copyright by Interviewbit


React Interview Questions

React Hooks Classes

It is used in functional It is used in class-based


components of React. components of React.

It will not require a It is necessary to declare the


declaration of any kind constructor inside the class
of constructor. component.

It does not require the Keyword this will be used in


use of this keyword state declaration ( this.state )
in state declaration or and in modification
modification. ( this.setState() ).

It is easier to use No specific function is available


because of the for helping us to access the state
useState and its corresponding setState
functionality. variable.

React Hooks can be Because of the long setup of


helpful in implementing state declarations, class states
Redux and context API. are generally not preferred.

32. How does the performance of using Hooks will differ in


comparison with the classes?
React Hooks will avoid a lot of overheads such as the instance creation, binding
of events, etc., that are present with classes.
Hooks in React will result in smaller component trees since they will be avoiding
the nesting that exists in HOCs (Higher Order Components) and will render props
which result in less amount of work to be done by React.

Page 46 © Copyright by Interviewbit


React Interview Questions

33. Do Hooks cover all the functionalities provided by the


classes?
Our goal is for Hooks to cover all the functionalities for classes at its earliest. There
are no Hook equivalents for the following methods that are not introduced in Hooks
yet:
getSnapshotBeforeUpdate()
getDerivedStateFromError()
componentDidCatch()

Since it is an early time for Hooks, few third-party libraries may not be compatible
with Hooks at present, but they will be added soon.

34. What is React Router?


React Router refers to the standard library used for routing in React. It permits us for
building a single-page web application in React with navigation without even
refreshing the page when the user navigates. It also allows to change the browser
URL and will keep the user interface in sync with the URL. React Router will make use
of the component structure for calling the components, using which appropriate
information can be shown. Since React is a component-based framework, it’s not
necessary to include and use this package. Any other compatible routing library
would also work with React.
The major components of React Router are given below:

Page 47 © Copyright by Interviewbit


React Interview Questions

BrowserRouter: It is a router implementation that will make use of the HTML5


history API (pushState, popstate, and event replaceState) for keeping your UI to
be in sync with the URL. It is the parent component useful in storing all other
components.
Routes: It is a newer component that has been introduced in the React v6 and
an upgrade of the component.
Route: It is considered to be a conditionally shown component and some UI will
be rendered by this whenever there is a match between its path and the current
URL.
Link: It is useful in creating links to various routes and implementing navigation
all over the application. It works similarly to the anchor tag in HTML.

35. Can React Hook replaces Redux?


The React Hook cannot be considered as a replacement for Redux (It is an open-
source, JavaScript library useful in managing the application state) when it comes to
the management of the global application state tree in large complex applications,
even though the React will provide a useReducer hook that manages state transitions
similar to Redux. Redux is very useful at a lower level of component hierarchy to
handle the pieces of a state which are dependent on each other, instead of a
declaration of multiple useState hooks.
In commercial web applications which is larger, the complexity will be high, so using
only React Hook may not be sufficient. Few developers will try to tackle the challenge
with the help of React Hooks and others will combine React Hooks with the Redux.

36. Explain conditional rendering in React.


Conditional rendering refers to the dynamic output of user interface markups based
on a condition state. It works in the same way as JavaScript conditions. Using
conditional rendering, it is possible to toggle specific application functions, API data
rendering, hide or show elements, decide permission levels, authentication handling,
and so on.
There are different approaches for implementing conditional rendering in React.
Some of them are:

Page 48 © Copyright by Interviewbit


React Interview Questions

Using if-else conditional logic which is suitable for smaller as well as for medium-
sized applications
Using ternary operators, which takes away some amount of complication from
if-else statements
Using element variables, which will enable us to write cleaner code.

37. Explain how to create a simple React Hooks example


program.
I will assume that you are having some coding knowledge about JavaScript and have
installed Node on your system for creating a below given React Hook program. An
installation of Node comes along with the command-line tools: npm and npx, where
npm is useful to install the packages into a project and npx is useful in running
commands of Node from the command line. The npx looks in the current project
folder for checking whether a command has been installed there. When the
command is not available on your computer, the npx will look in the npmjs.com
repository, then the latest version of the command script will be loaded and will run
without locally installing it. This feature is useful in creating a skeleton React
application within a few key presses.
Open the Terminal inside the folder of your choice, and run the following command:

npx create-react-app react-items-with-hooks

Here, the create-react-app is an app initializer created by Facebook, to help with


the easy and quick creation of React application, providing options to customize it
while creating the application? The above command will create a new folder named
react-items-with-hooks and it will be initialized with a basic React application. Now,
you will be able to open the project in your favourite IDE. You can see an src folder
inside the project along with the main application component App.js . This file is
having a single function App() which will return an element and it will make use of
an extended JavaScript syntax(JSX) for defining the component.

Page 49 © Copyright by Interviewbit


React Interview Questions

JSX will permit you for writing HTML-style template syntax directly into the
JavaScript file. This mixture of JavaScript and HTML will be converted by React
toolchain into pure JavaScript that will render the HTML element.
It is possible to define your own React components by writing a function that will
return a JSX element. You can try this by creating a new file src/SearchItem.js and
put the following code into it.

import React from 'react';


export function SearchItem() {
return (
<div>
<div className="search-input">
<input type="text" placeholder="SearchItem"/>
</div>
<h1 className="h1">Search Results</h1>
<div className="items">
<table>
<thead>
<tr>
<th className="itemname-col">Item Name</th>
<th className="price-col">Price</th>
<th className="quantity-col">Quantity</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
);
}

This is all about how you can create a component. It will only display the empty table
and doesn’t do anything. But you will be able to use the Search component in the
application. Open the file src/App.js and add the import statement given below to
the top of the file.

import { SearchItem } from './SearchItem';

Now, from the logo.svg, import will be removed and then contents of returned value
in the function App() will be replaced with the following code:

Page 50 © Copyright by Interviewbit


React Interview Questions

<div className="App">
<header>
Items with Hooks
</header>
<SearchItem/>
</div>

You can notice that the element <SearchItem/> has been used just similar to an
HTML element. The JSX syntax will enable for including the components in this
approach directly within the JavaScript code. Your application can be tested by
running the below-given command in your terminal.
npm start

This command will compile your application and open your default browser into
http://localhost:4000. This command can be kept on running when code
development is in progress to make sure that the application is up-to-date, and also
this browser page will be reloaded each time you modify and save the code.
This application will work finely, but it doesn’t look nice as it doesn’t react to any
input from the user. You can make it more interactive by adding a state with React
Hooks, adding authentication, etc.

38. How to create a switching component for displaying


different pages?
A switching component refers to a component that will render one of the multiple
components. We should use an object for mapping prop values to components.
A below-given example will show you how to display different pages based on page
prop using switching component:

Page 51 © Copyright by Interviewbit


React Interview Questions

import HomePage from './HomePage'


import AboutPage from './AboutPage'
import FacilitiesPage from './FacilitiesPage'
import ContactPage from './ContactPage'
import HelpPage from './HelpPage'
const PAGES = {
home: HomePage,
about: AboutPage,
facilitiess: FacilitiesPage,
contact: ContactPage
help: HelpPage
}
const Page = (props) => {
const Handler = PAGES[props.page] || HelpPage
return <Handler {...props} />
}
// The PAGES object keys can be used in the prop types for catching errors during dev-t
Page.propTypes = {
page: PropTypes.oneOf(Object.keys(PAGES)).isRequired
}

39. How to re-render the view when the browser is resized?


It is possible to listen to the resize event in componentDidMount() and then update
the width and height dimensions. It requires the removal of the event listener in the
componentWillUnmount() method.
Using the below-given code, we can render the view when the browser is resized.

Page 52 © Copyright by Interviewbit


React Interview Questions

class WindowSizeDimensions extends React.Component {


constructor(props){
super(props);
this.updateDimension = this.updateDimension.bind(this);
}

componentWillMount() {
this.updateDimension()
}
componentDidMount() {
window.addEventListener('resize', this.updateDimension)
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateDimension)
}
updateDimension() {
this.setState({width: window.innerWidth, height: window.innerHeight})
}
render() {
return <span>{this.state.width} x {this.state.height}</span>
}
}

40. How to pass data between sibling components using React


router?
Passing data between sibling components of React is possible using React Router
with the help of history.push and match.params .
In the code given below, we have a Parent component AppDemo.js and have two
Child Components HomePage and AboutPage . Everything is kept inside a Router by
using React-router Route. It is also having a route for /about/{params} where we will
pass the data.

Page 53 © Copyright by Interviewbit


React Interview Questions

import React, { Component } from ‘react’;


class AppDemo extends Component {
render() {
return (
<Router>
<div className="AppDemo">
<ul>
<li>
<NavLink to="/" activeStyle={{ color:'blue' }}>Home</NavLink>
</li>
<li>
<NavLink to="/about" activeStyle={{ color:'blue' }}>About
</NavLink>
</li>
</ul>
<Route path="/about/:aboutId" component={AboutPage} />
<Route path="/about" component={AboutPage} />
<Route path="/" component={HomePage} />
</div>
</Router>
);
}
}
export default AppDemo;

The HomePage is a functional component with a button. On button click, we are


using props.history.push(‘/about/’ + data) to programmatically navigate into
/about/data .

export default function HomePage(props) {


const handleClick = (data) => {
props.history.push('/about/' + data);
}
return (
<div>
<button onClick={() => handleClick('DemoButton')}>To About</button>
</div>
)
}

Also, the functional component AboutPage will obtain the data passed by
props.match.params.aboutId .

Page 54 © Copyright by Interviewbit


React Interview Questions

export default function AboutPage(props) {


if(!props.match.params.aboutId) {
return <div>No Data Yet</div>
}
return (
<div>
{`Data obtained from HomePage is ${props.match.params.aboutId}`}
</div>
)
}

A er button click in the HomePage the page will look like below:

41. How to perform automatic redirect a er login?


The react-router package will provide the component <Redirect> in React Router.
Rendering of a <Redirect> component will navigate to a newer location. In the
history stack, the current location will be overridden by the new location just like the
server-side redirects.

import React, { Component } from 'react'


import { Redirect } from 'react-router'
export default class LoginDemoComponent extends Component {
render() {
if (this.state.isLoggedIn === true) {
return <Redirect to="/your/redirect/page" />
} else {
return <div>{'Please complete login'}</div>
}
}
}

Page 55 © Copyright by Interviewbit


React Interview Questions

Conclusion
React has got more popularity among the top IT companies like Facebook, PayPal,
Instagram, Uber, etc., around the world especially in India. Hooks is becoming a trend
in the React community as it removes the state management complexities.
This article includes the most frequently asked ReactJS and React Hooks interview
questions and answers that will help you in interview preparations. Also, remember
that your success during the interview is not all about your technical skills, it will also
be based on your state of mind and the good impression that you will make at first.
All the best!!
Useful References and Resources:
"Beginning React with Hooks " book by Greg Lim
“Learn React Hooks” book by Daniel Bugl
Node.js vs React.js
React Native Interview Questions

Page 56 © Copyright by Interviewbit


Links to More Interview
Questions

C Interview Questions Php Interview Questions C Sharp Interview Questions

Web Api Interview Hibernate Interview Node Js Interview Questions


Questions Questions

Cpp Interview Questions Oops Interview Questions Devops Interview Questions

Machine Learning Interview Docker Interview Questions Mysql Interview Questions


Questions

Css Interview Questions Laravel Interview Questions Asp Net Interview Questions

Django Interview Questions Dot Net Interview Questions Kubernetes Interview


Questions

Operating System Interview React Native Interview Aws Interview Questions


Questions Questions

Git Interview Questions Java 8 Interview Questions Mongodb Interview


Questions

Dbms Interview Questions Spring Boot Interview Power Bi Interview Questions


Questions

Pl Sql Interview Questions Tableau Interview Linux Interview Questions


Questions

Ansible Interview Questions Java Interview Questions Jenkins Interview Questions

Page 57 © Copyright by Interviewbit


UNDERSTAND
DEBOUNCING
IN REACT
MUKUL
RAJPOOT
PROBLEM?
Have you encountered issues with
functions being called multiple times
when you only intended them to
execute once? This can happen
during user input events or scrolling,
leading to performance problems
and undesired behavior. Debouncing
provides a solution to this problem.

MUKUL
RAJPOOT
WHAT?
Debouncing is a technique that
ensures a function is executed only
after a certain period of inactivity. It
improves efficiency and prevents
unnecessary function calls.

MUKUL
RAJPOOT
STEPS?
1️⃣ Event-Triggered: Start with an event that
you want to handle efficiently, like user
input or scrolling.

2️⃣ Waiting Period: After each event, start a


timer. If another event occurs within the
waiting period, reset the timer.

3️⃣ Execution: The function is executed once


the waiting period elapses without any new
events, minimizing unnecessary
computations.

MUKUL
RAJPOOT
APPLICATION?
Debouncing is commonly used in
scenarios like autocomplete search,
resizing windows, and handling scroll
events. It helps create smoother user
experiences and optimizes your
applications.

MUKUL
RAJPOOT
EXAMPLE?
EXAMPLE?
In above code, we're using the setTimeout
function to implement a simple
debouncing mechanism. Whenever the
searchTerm state changes, the useEffect
hook sets up a timer to execute the search
logic after a delay of 300 milliseconds.

If another searchTerm change occurs


within the 300ms delay, the previous
timer is cleared, and a new timer is set up.
This ensures that the search logic is only
triggered after a period of inactivity.

MUKUL
RAJPOOT
BENEFITS?
Implementing debouncing
techniques in your web development
projects offers several benefits:
Smoother user experiences
Reduced server load
Improved performance

MUKUL
RAJPOOT
FOLLOW
MUKUL RAJPOOT
FOR MORE SUCH
CONTENT

THANKS
100 React
Interview Q&A
Made by Want More

1. What is React?

React is a popular JavaScript library for building user interfaces. It allows


developers to create reusable UI components and efficiently update and
render them based on changes in data.

2. What are the key features of React?

Some key features of React include:

Virtual DOM: React uses a virtual representation of the actual DOM,


which improves performance by minimizing direct manipulations to
the real DOM.
Component-based architecture: React promotes the creation of
reusable UI components.
One-way data flow: React follows a unidirectional data flow, making it
easier to track and manage changes in the application state.
JSX: React uses JSX, a syntax extension that allows you to write HTML-
like code within JavaScript.

3. What is JSX in React?

JSX is a syntax extension used in React that allows you to write HTML-like
code within JavaScript. It provides a convenient way to define the
structure and appearance of React components.

4. What is the difference between React and React Native?

React is a library for building web applications, while React Native is a


framework for building native mobile applications. React Native allows
you to write components using React syntax, but it compiles them to
native code rather than rendering them as HTML elements.

5. What is a functional component in React?


A functional component, also known as a stateless component, is a
JavaScript function that returns JSX to define the structure and
appearance of a React component. Functional components are primarily
used for presenting UI and don't have their own internal state.

6. What is a class component in React?

A class component is a JavaScript class that extends the React.Component


class. It uses the render() method to define the structure and appearance
of a React component. Class components can have their own state and
lifecycle methods.

7. What is the difference between functional and class components?

Functional components are simpler and easier to read and test compared
to class components. They don't have their own state or lifecycle methods.
Class components, on the other hand, can manage their own state and
have access to lifecycle methods such as componentDidMount() and
componentDidUpdate().

8. What is state in React?

State is a built-in object in React that holds component-specific data. It


represents the mutable values that can change over time and trigger a re-
render of the component.

9. What is props in React?

Props (short for properties) are used to pass data from a parent
component to a child component. Props are read-only and cannot be
modified by the child component. They are passed as attributes to the
child component in JSX.

10. What is the purpose of the virtual DOM in React?

The virtual DOM is a lightweight copy of the actual DOM maintained by


React. It allows React to perform efficient updates and minimize direct
manipulations to the real DOM. React compares the virtual DOM with the
previous version and updates only the necessary parts, improving
performance.

11. What is a React component lifecycle?

React component lifecycle refers to a series of phases that a component


goes through from initialization to destruction. The key lifecycle methods
are:

Mounting: constructor(), render(), componentDidMount()


Updating: render(), componentDidUpdate()
Unmounting: componentWillUnmount()

12. What is the significance of the render() method in React?

The render() method is a required method in React components. It returns


JSX that describes the structure and appearance of the component. The
render() method is called whenever the component needs to be re-
rendered due to changes in props or state.

13. What is the purpose of the componentDidMount() method?

The componentDidMount() method is a lifecycle method that is called


after a component has been mounted (inserted into the DOM). It is
commonly used for performing side effects, such as fetching data from an
API orsubscribing to events.

14. What is the difference between controlled and uncontrolled


components in React?

In a controlled component, the value of the form elements is controlled by


React. The component's state is used to manage the value, and any
changes to the value are handled by updating the state. In an
uncontrolled component, the value of the form elements is managed by
the DOM itself, and React doesn't control or track the value.

15. What is the purpose of keys in React lists?

Keys are used in React lists to give each item a unique identifier. They help
React identify which items have changed, been added, or been removed
in a list, improving performance and avoiding unnecessary re-rendering of
components.

16. What are React refs used for?

Refs are used in React to get direct access to a DOM element or a React
component instance. They provide a way to interact with the underlying
DOM or component imperatively, outside of the typical React data flow.

17. What is conditional rendering in React?

Conditional rendering in React allows you to render different content or


components based on certain conditions or state. It enables dynamic
rendering and helps in creating responsive and interactive UIs.

18. What is the purpose of the shouldComponentUpdate() method?

The shouldComponentUpdate() method is a lifecycle method that allows


you to optimize performance by controlling whether or not a component
should re-render. By implementing this method, you can compare the
current props and state with the next props and state and decide if a re-
render is necessary.

19. What are React Hooks?

React Hooks are functions introduced in React 16.8 that allow you to use
state and other React features in functional components. Hooks provide a
way to use local component state, lifecycle methods, and other React
features without writing a class.

20. What is the useState() Hook used for?

The useState() Hook is a built-in Hook in React that allows functional


components to manage local state. It returns an array with two elements:
the current state value and a function to update the state. It replaces the
need for using a class and this.setState() to manage state.

21. What is the useContext() Hook used for?

The useContext() Hook is a built-in Hook in React that allows functional


components to access a context directly. It retrieves the current value of a
context and subscribes the component to updates when the context value
changes.

22. What is the useEffect() Hook used for?

The useEffect() Hook is a built-in Hook in React that allows functional


components to perform side effects. It replaces the lifecycle methods like
componentDidMount(), componentDidUpdate(), and
componentWillUnmount(). The useEffect() Hook runs after every render by
default.

23. What is the purpose of the useMemo() Hook?

The useMemo() Hook is a built-in Hook in React that memoizes the result
of a computation and returns the cached result when the dependencies
haven't changed. It helps in optimizing performance by avoiding
unnecessary expensive calculations.
24. What is the useReducer() Hook used for?

The useReducer() Hook is a built-in Hook in React that provides a way to


manage complex state logic in a predictable way. It is an alternative to
useState() for managing state when the state transitions are more
complex and involve multiple sub-values.

25. What is React Router used for?

React Router is a popular library for routing in React applications. It


provides a way to handle navigation and routing between different
components and views in a single-page application.

26. What are React Fragments?

React Fragments are a feature in React that allows you to group a list of
children without adding extra nodes to the DOM. They are useful when
you need to return multiple elements from a component's render()
method, but they don't need a parent container element.

27. What is the purpose of the useCallback() Hook?

The useCallback() Hook is a built-in Hook in React that returns a


memoized version of the callback function that only changes if one of the
dependencies has changed. It helps in optimizing performance by
preventing unnecessary re-rendering of components that depend on the
callback.

28. What is the purpose of the useRef() Hook?

The useRef() Hook is a built-in Hook in React that provides a way to create
a mutable reference that persists across re-renders of a component. It can
be used to access DOM elements or store mutable values that won't
trigger re-renders.

29. What is React context?

React context provides a way to pass data through the component tree
without having to pass props manually at every level. It allows you to
create a global state accessible to all components within a context
provider.

30. What is the significance of the displayName property in React?


The displayName property is an optional property that you can define on a
React component. It is used by React in debugging messages and
component identification. It helps in identifying components in React
DevTools and error messages.

31. What is the purpose of the dangerouslySetInnerHTML attribute in


React?

The dangerouslySetInnerHTML attribute is used in React to render raw


HTML content inside a component. It is typically used when you need to
render HTML received from an external source, but you need to be
cautious as it can expose your application to cross-site scripting (XSS)
attacks if used improperly.

32. What is the difference between a controlled and an uncontrolled


component in React forms?

In a controlled component, the value of the form input is controlled by


React using the value prop, and any changes to the input value are
handled by updating the state. In an uncontrolled component, the value of
the form input is managed by the DOM, and React doesn't control or track
the value.

33. What is the purpose of the React Developer Tools extension?

The React Developer Tools extension is a browser extension that helps in


debugging and inspecting React component hierarchies. It provides a
visual representation of component trees, allows inspection of component
props and state, and helps in understanding the component's lifecycle.

34. How can you optimize performance in React applications?

Some techniques to optimize performance in React applications include:

Using React.memo() to memoize functional components


Using shouldComponentUpdate() or React.memo() to prevent
unnecessary re-renders
Using useMemo() or useCallback() to memoize expensive calculations
or event handlers
Using lazy loading and code splitting to load components on-demand
Optimizing list rendering using keys and React's reconciliation
algorithm

35. What is the purpose of the PureComponent in React?


The PureComponent is a base class in React that automatically
implements the shouldComponentUpdate() method with a shallow prop
and state comparison. It helps in optimizing performance by preventing
unnecessary re-renders when the prop and state values haven't changed.

36. What is the difference between createElement and JSX?

createElement is a method provided by React to create React elements


programmatically. JSX, on the other hand, is a syntax extension that allows
you to write HTML-like code within JavaScript, which is then transpiled to
createElement calls during the build process.

37. What is the significance of the key prop in React lists?

The key prop is used in React lists to give each item a unique identifier. It
helps React identify which items have changed, been added, or been
removed in a list, improving performance and avoiding unnecessary re-
rendering of components.

38. What is the purpose of the componentDidCatch() method?

The componentDidCatch() method is a lifecycle method in React that is


called when an error occurs during rendering, in a lifecycle method, or in
the constructor of any child component. It provides an opportunity to
handle the error gracefully and display an error message.

39. What is ReactRouter's history object used for?

React Router's history object is used for programmatically navigating


between different routes in a React application. It provides methods and
properties for managing the browser history, such as pushing new routes,
replacing the current route, or going back and forward in the history.

40. What is the purpose of the withRouter() higher-order component in


React Router?

The withRouter() higher-order component is used in React Router to wrap


a component and provide access to the router's history, match, and
location objects. It allows a component that is not directly rendered by a
Route component to access the router-related props.

41. What is the difference between the react-router-dom and react-


router-native packages?
The react-router-dom package is used for routing in web applications built
with React, while the react-router-native package is used for routing in
React Native applications. The core functionality of routing is the same,
but the packages provide different implementations based on the target
platform.

42. What is the purpose of the react-transition-group library?

The react-transition-group library is used to create animated transitions in


React components. It provides a way to animate the mounting and
unmounting of components and allows for easy integration with CSS
transitions or animations.

43. What is the React Context API and when is it useful?

The React Context API provides a way to share data across a component
tree without manually passing props down through every level. It is useful
when you have data that needs to be accessed by multiple components at
different levels in the component hierarchy.

44. What is the purpose of the useCallback() Hook in React?

The useCallback() Hook is used to memoize a function. It returns a


memoized version of the function that only changes if one of the
dependencies has changed. It is useful when passing callbacks to child
components to prevent unnecessary re-renders.

45. What is the React DevTools Profiler used for?

The React DevTools Profiler is a tool used for profiling and optimizing the
performance of React applications. It allows you to analyze and measure
component render times and interactions to identify performance
bottlenecks and optimize your application.

46. What is the purpose of the react-router-config package?

The react-router-config package is used to configure and render routes in


React Router. It provides a way to define routes as a configuration object
or array, making it easier to manage and maintain route configurations in
large applications.

47. What are React Hooks rules or guidelines?

Some rules or guidelines for using React Hooks include:


Hooks should only be used in functional components or custom Hooks,
not in regular JavaScript functions or class components.
Hooks should be called at the top level of a functional component, not
within loops, conditions, or nested functions.
Hooks should always be called in the same order in every render of a
component.
Hooks should not be called conditionally based on some condition or
branch of code.
Custom Hooks should always start with the word "use" to indicate that
they follow the rules of Hooks.

48. What is the purpose of the react-router-dom's Link component?

The Link component in react-router-dom is used to create links to


different routes in a React application. It allows for easy navigation
between different views without reloading the page and provides a
declarativeway to define navigation links.

49. What is the purpose of the React.StrictMode component?

The React.StrictMode component is used to highlight potential problems


in a React application during development. It enables additional checks
and warnings, and helps in identifying common mistakes or anti-patterns.

50. How can you handle form submissions in React?

To handle form submissions in React, you can use the onSubmit event
handler on the form element. You can prevent the default form
submission behavior using event.preventDefault() and then access the
form data from the event object to perform further processing or submit
data to a server.

You might also like