React Interview Question
React Interview Question
1. What is React?
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.
It will make use of the virtual DOM rather than real DOM (Data Object Model) as RealDOM
manipulations are expensive.
Real-Life Problems
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
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.
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.
The components of React are numerous and will take time to fully grasp the benefits of all.
Coding might become complex as it will make use of inline templating and JSX.
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(...);
...
};
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.
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.
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.
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.
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>
)
}
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:
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>
)
}
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:
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.
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.
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
**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. After 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.
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.
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>
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.
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.
The main purpose of props is to provide different component functionalities such as:
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; .
React StateEvery 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.
Example:
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 Class component:
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.
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 after 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.
Any component which uses one of the following lifecycle methods is considered an error boundary.
1. Render phase
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.
In the code above, getDerivedStateFromError function renders the fallback UI interface when the
render method has an error.
Now with the error boundary, we can render the CounterComponent in the following way:
<ErrorBoundary>
<CounterComponent/>
</ErrorBoundary>
React Hooks cannot be used in class components. They let us write components without class.
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.
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('');
}
The state variable “name” can be directly used inside the HTML.
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 after 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]) .
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.
🧠“What
1. Confidence starter (jab interviewer bole “Tell me about yourself” ya
do you know about React?”)
“I’ve worked with React to build interactive and component-based user interfaces.
I really like how React follows a declarative approach and helps manage UI updates efficiently
using the Virtual DOM.”
It gives both flexibility and performance — that’s what I like the most about it.”
I prefer breaking down the issue into smaller parts, isolating the component, and then fixing it
logically instead of randomly changing code.”
Also, I try to keep components small and avoid deep prop drilling by using Context API when
needed.”
🔥 10. When interview ends and they say “Any questions for us?”
“Yes, I’d love to know how interns contribute to live projects here —
whether we get to work directly with senior developers or focus on independent tasks.”