React
React
REACT
Interview
Questions
Contents
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.
...
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.
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.
***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 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
co m po nent s.
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:
Handling props
Let’s render the following component with props and analyse how functional and
class components handle props:
function StudentInfo(props){
return(
<div className="main">
<h2>{props.name}</h2>
<h4>{props.rollNumber}</h4>
</div>
)
}
<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
co m po nent s.
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:
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:
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
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?
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.
One-time
va l ue
retrieval ✔ ✔ ✔
(e.g. on
s ubmi t )
Validating on
✔ ✔ ✔
s ubmi t
Fi el d- l evel
Validation ❌ ✔ ✔
Conditionally
disabling
s ubmi t
but t on ❌ ✔ ✔
Enforcing
input format
s evera l ❌ ✔ ✔
inputs for
one piece of
data
dyna mi c ❌ ✔ ✔
i nput s
❌ ✔
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.
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:
Props State
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:
<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.
<Car brand="Mercedes"/>
In Functional component:
function Car(props) {
let [brand, setBrand] = useState(props.brand);
}
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.
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?
In the code above, when the counterValue equals 2, we throw an error inside the
render method.
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:
<ErrorBoundary>
<CounterComponent/>
</ErrorBoundary>
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('');
}
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.
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:
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.
function App() {
return (
<React.StrictMode>
<div classname="App">
<Header/>
<div>
Page Content
</div>
<Footer/>
</div>
</React.StrictMode>
);
}
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.
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:
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.
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>
);
}
}
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:
render() {
return (
<div>
<h3 className="heading">This is a heading</h3>
<p className={styles.paragraph} >This is a paragraph</p>
</div>
);
}
}
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.
<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:
function ChildComponent(props) {
return (
<div>
<p>Value of counter: {props.counterValue}</p>
</div>
);
}
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.
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.
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:
<div>
{this.state.articles.map((article) => (
<ArticleData article={article} key={article.id} />
))}
</div>
);
}
}
<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:
Using the concept of Higher-Order Components, we can now render the ArticlesList
and UsersList components in the following way:
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:
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
co m po nent s.
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.
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.
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.
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.jsand
put the following code into it.
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.
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:
<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:
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>
}
}
Also, the functional component AboutPage will obtain the data passed by
props.match.params.aboutId .
A er button click in the HomePage the page will look like below:
Co ncl usio n
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: