How is React Router different from Conventional Routing?
The difference between React Routing and Conventional Routing are:
SN | Conventional Routing | React Routing |
---|---|---|
1. | In Conventional Routing, each view contains a new file. | In React Routing, there is only a single HTML page involved. |
2. | The HTTP request is sent to a server to receive the corresponding HTML page. | Only the History attribute <BrowserRouter> is changed. |
3. | In this, the user navigates across different pages for each view. | In this, the user is thinking he is navigating across different pages, but its an illusion only. |
Why you get “Router may have only one child element” warning?
It is because you have not to wrap your Route’s in a <Switch> block or <div> block which renders a route exclusively.
Example
render((
<Router>
<Route {/* ... */} />
<Route {/* ... */} />
</Router>
)
should be
render(
<Router>
<Switch>
<Route {/* ... */} />
<Route {/* ... */} />
</Switch>
</Router>
)
Why switch keyword used in React Router v4?
The ‘switch’ keyword is used to display only a single Route to rendered amongst the several defined Routes. The <Switch> component is used to render components only when the path will be matched. Otherwise, it returns to the not found component.
React JS Interview Question
How to use styles in React?
We can use style attribute for styling in React applications, which adds dynamically-computed styles at render time. It accepts a JavaScript object in camelCased properties rather than a CSS string. The style attribute is consistent with accessing the properties on DOM nodes in JavaScript.
Example
const divStyle = {
color: 'blue',
backgroundImage: 'url(' + imgUrl + ')'
};
function HelloWorldComponent() {
return <div style={divStyle}>Hello World!</div>
}
How many ways can we style the React Component?
We can style React Component in mainly four ways, which are given below:
- Inline Styling
- CSS Stylesheet
- CSS Module
- Styled Components
Explain CSS Module styling in React.
CSS Module is a CSS file where all class names and animation names are scoped locally by default. It is available only for the component which imports it, and without your permission, it cannot be applied to any other Components. You can create CSS Module file with the .module.css extension.
Advance React JS Interview Question
What are Styled Components?
Styled-Components is a library for React. It is the successor of CSS Modules. It uses enhance CSS for styling React component systems in your application, which is written with a mixture of JavaScript and CSS. It is scoped to a single component and cannot leak to any other element in the page.
The styled-components provides:
- Automatic critical CSS
- No class name bugs
- Easier deletion of CSS
- Simple dynamic styling
- Painless maintenance
What are hooks in React?
Hooks are the new feature introduced in React 16.8 version that facilitates us to use state and other React features without writing a class.
See the following example of use State hook:
import { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click on this button
</button>
</div>
);
}
What are the rules you should follow for the hooks in React?
We have to follow the following two rules to use hooks in React:
- You should call hooks only at the top level of your React functions and not inside the loops, conditions, or nested functions. This is used to ensure that hooks are called in the same order each time a component renders, and it also preserves the state of hooks between multiple use State and use Effect calls.
- You should call hooks from React functions only. Don’t call hooks from regular JavaScript functions.
React JS Interview Question
What are forms in React?
In React, forms are used to enable users to interact with web applications. Following is a list of the most common usage of forms in React:
- Forms facilitate users to interact with the application. By using forms, the users can communicate with the application and enter the required information whenever required.
- Forms contain certain elements, such as text fields, buttons, checkboxes, radio buttons, etc., that can make the application more interactive and beautiful.
- Forms are the best possible way to take inputs from the users.
- Forms are used for many different tasks such as user authentication, searching, filtering, indexing, etc.
What is an error boundary or error boundaries?
An error boundary is a concept introduced in version 16 of React. Error boundaries provide a way to find out the errors that occur in the render phase. Any component which uses one of the following lifecycle methods is considered an error boundary. Let’s see the places where an error boundary can detect an error:
- Render phase
- Inside a lifecycle method
- Inside the constructor
Let’s see an example to understand it better:
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 above code, you can see that when the counterValue equals 2, it throws an error inside the render method. We know that any error inside the render method leads to unmounting of the component so, to display an error that occurs inside the render method, we use error boundaries. When we are not using the error boundary, we see a blank page instead of seeing an error.
With error boundaries:
We have specified earlier that error boundary is a component using one or both of the following methods:
- static get Derived State From Error
- component Did Catch
See the following code where we create an error boundary to handle errors in 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;
}
}
You can see in the above code the getDerivedStateFromError function renders the fallback UI interface when the render method has an error.
The componentDidCatch logs the error information to an error tracking service.
Now with error boundary, we can render the Counter Component in the following way:
<ErrorBoundary>
<CounterComponent/>
</ErrorBoundary>
In which cases do error boundaries not catch errors?
Following are some cases in which error boundaries don’t catch errors:
- Error boundaries don’t catch errors inside the event handlers.
- During the server-side rendering.
- In the case when errors are thrown in the error boundary code itself.
- Asynchronous code using set Timeout or requestAnimationFrame callbacks.
Advance React JS Interview Question
What were the major problems with MVC framework?
The major problems with the MVC framework are:
- DOM manipulation was very expensive.
- It makes the application slow and inefficient.
- There was a huge memory wastage.
- It makes the application debugging hard.
Explain the Flux concept.
Flux is an application architecture that Facebook uses internally for building the client-side web application with React. It is neither a library nor a framework. It is a kind of architecture that complements React as view and follows the concept of Unidirectional Data Flow model. It is useful when the project has dynamic data, and we need to keep the data updated in an effective manner.

What is Redux?
Redux is an open-source JavaScript library used to manage application state. React uses Redux for building the user interface. The Redux application is easy to test and can run in different environments showing consistent behavior. It was first introduced by Dan Abramov and Andrew Clark in 2015.
React Redux is the official React binding for Redux. It allows React components to read data from a Redux Store, and dispatch Actions to the Store to update data. Redux helps apps to scale by providing a sensible way to manage state through a unidirectional data flow model. React Redux is conceptually simple. It subscribes to the Redux store, checks to see if the data which your component wants have changed, and re-renders your component.
React JS Interview Question
What are the three principles that Redux follows?
The three principles that redux follows are:
- Single source of truth: The State of your entire application is stored in an object/state tree inside a single Store. The single State tree makes it easier to keep changes over time. It also makes it easier to debug or inspect the application.
- The State is read-only: There is only one way to change the State is to emit an action, an object describing what happened. This principle ensures that neither the views nor the network callbacks can write directly to the State.
- Changes are made with pure functions: To specify how actions transform the state tree, you need to write reducers (pure functions). Pure functions take the previous State and Action as a parameter and return a new State.
List down the components of Redux.
The components of Redux are given below.
- STORE: A Store is a place where the entire State of your application lists. It is like a brain responsible for all moving parts in Redux.
- ACTION: It is an object which describes what happened.
- REDUCER: It determines how the State will change.
Explain the role of Reducer.
Reducers read the payloads from the actions and then updates the Store via the State accordingly. It is a pure function which returns a new state from the initial State. It returns the previous State as it is if no work needs to be done.
Advance React JS Interview Question
What is the significance of Store in Redux?
A Store is an object which holds the application’s State and provides methods to access the State, dispatch Actions and register listeners via subscribe(listener). The entire State tree of an application is saved in a single Store which makes the Redux simple and predictable. We can pass middleware to the Store which handles the processing of data as well as keep a log of various actions that change the Store’s State. All the Actions return a new state via reducers.
How is Redux different from Flux?
The Redux is different from Flux in the following manner.
SN | Redux | Flux |
---|---|---|
1. | Redux is an open-source JavaScript library used to manage application State. | Flux is neither a library nor a framework. It is a kind of architecture that complements React as view and follows the concept of Unidirectional Data Flow model. |
2. | Store’s State is immutable. | Store’s State is mutable. |
3. | In this, Store and change logic are separate. | In this, the Store contains State and change logic. |
4. | It has only a single Store. | It can have multiple Store. |
5. | Redux does not have Dispatcher concept. | It has single Dispatcher, and all actions pass through that Dispatcher. |
What are the advantages of Redux?
The main advantages of React Redux are:
- React Redux is the official UI bindings for react Application. It is kept up-to-date with any API changes to ensure that your React components behave as expected.
- It encourages good ‘React’ architecture.
- It implements many performance optimizations internally, which allows to components re-render only when it actually needs.
- It makes the code maintenance easy.
- Redux’s code written as functions which are small, pure, and isolated, which makes the code testable and independent.
React JS Interview Question
How to access the Redux store outside a component?
You need to export the Store from the module where it created with create Store() method. Also, you need to assure that it will not pollute the global window space.
store = createStore(myReducer)
export default store
Why use React instead of other frameworks, like Angular?
Easy creation of dynamic applications: React makes it easier to create dynamic web applications because it provides less coding and provides more functionality, whereas, with JavaScript applications, code tends to get complex very quickly. | |
Improved performance: React uses virtual DOM, which makes web applications perform faster. Virtual DOM compares its previous state and updates only those components in the real DOM, whose states have changed, rather than updating all the components — like conventional web applications. | |
Reusable components: Components are the building blocks of any React application, and a single app usually consists of multiple components. These components have their own logic and controls, and they can be reused through the application, which, in turn, dramatically reduces the development time of an application. | |
Unidirectional data flow: React follows a unidirectional data flow. This means that when designing a React app, we often nest child components within parent components. And since the data flows in a single direction, it becomes easier to debug errors and know where the problem occurs in an application at the moment. | |
Dedicated tools for easy debugging: Facebook has released a chrome extension that we can use to debug React applications. This makes the process of debugging React to web applications faster and easier. |
What is the difference between the ES6 and ES5 standards?
These are the few instances where ES6 syntax has changed from ES5 syntax:
- Components and Function
- exports vs export
- require vs import
Advance React JS Interview Question
How do you create a React app?
These are the steps for creating a React app:
- Install NodeJS on the computer because we need npm to install the React library. Npm is the node package manager that contains many JavaScript libraries, including React.
- Install the create-react-app package using the command prompt or terminal.
- Install a text editor of your choice, like VS Code or Sublime Text.
Explain how lists work in React
- We create lists in React as we do in regular JavaScript. Lists display data in an ordered format
- The traversal of lists is done using the map() function
Why is there a need for using keys in Lists?
Keys are very important in lists for the following reasons:
- A key is a unique identifier and it is used to identify which items have changed, been updated or deleted from the lists
- It also helps to determine which components need to be re-rendered instead of re-rendering all the components every time. Therefore, it increases performance, as only the updated components are re-rendered
React JS Interview Question
What are forms in React?
React employs forms to enable users to interact with web applications.
- Using forms, users can interact with the application and enter the required information whenever needed. Form contain certain elements, such as text fields, buttons, checkboxes, radio buttons, etc
- Forms are used for many different tasks such as user authentication, searching, filtering, indexing, etc
How do you create forms in React?
We create forms in React by doing the following:
The above code will yield an input field with the label Name and a submit button. It will also alert the user when the submit button is pressed.
How do you write comments in React?
There are basically two ways in which we can write comments:
- Single-line comments
- Multi-line comments
Advance React JS Interview Question
What is an arrow function and how is it used in React?
- An arrow function is a short way of writing a function to React.
- It is unnecessary to bind ‘this’ inside the constructor when using an arrow function. This prevents bugs caused by the use of ‘this’ in React callbacks.
What are the components in React?
Components are the building blocks of any React application, and a single app usually consists of multiple components. A component is essentially a piece of the user interface. It splits the user interface into independent, reusable parts that can be processed separately.
There are two types of components in React:
- Functional Components: These types of components have no state of their own and only contain render methods, and therefore are also called stateless components. They may derive data from other components as props (properties).
function Greeting(props) {
return <h1>Welcome to {props.name}</h1>;
}
- Class Components: These types of components can hold and manage their own state and have a separate render method to return JSX on the screen. They are also called Stateful components as they can have a state.
class Greeting extends React.Component {
render() {
return <h1>Welcome to {this.props.name}</h1>;
}
}
What is the use of render() in React?
- It is required for each component to have a render() function. This function returns the HTML, which is to be displayed in the component.
- If you need to render more than one element, all of the elements must be inside one parent tag like <div>, <form>.
React JS Interview Question
How do you update the state of a component?
We can update the state of a component by using the built-in ‘set State()’ method:
What is a higher-order component in React?
A higher-order component acts as a container for other components. This helps to keep components simple and enables re-usability. They are generally used when multiple components have to use a common logic.
Explain the lifecycle methods of components.
- getInitialState(): This is executed before the creation of the component.
- componentDidMount(): Is executed when the component gets rendered and placed on the DOM.
- shouldComponentUpdate(): Is invoked when a component determines changes to the DOM and returns a “true” or “false” value based on certain conditions.
- componentDidUpdate(): Is invoked immediately after rendering takes place.
- componentWillUnmount(): Is invoked immediately before a component is destroyed and unmounted permanently.
So far, if you have any doubts about the above React interview questions and answers, please ask your questions in the section below.
Advance React JS Interview Question
What is Redux?
Redux is an open-source, JavaScript library used to manage the application state. React uses Redux to build the user interface. It is a predictable state container for JavaScript applications and is used for the entire application’s state management.
What are the components of Redux?
- Store: Holds the state of the application.
- Action: The source information for the store.
- Reducer: Specifies how the application’s state changes in response to actions sent to the store.
What is the Flux?
- Flux is the application architecture that Facebook uses for building web applications. It is a method of handling complex data inside a client-side application and manages how data flows in a React application.
- There is a single source of data (the store) and triggering certain actions is the only way way to update them.The actions call the dispatcher, and then the store is triggered and updated with their own data accordingly.
- When a dispatch has been triggered, and the store updates, it will emit a change event that the views can rerender accordingly.
React JS Interview Question
Why do we need to React Router?
- It maintains consistent structure and behavior and is used to develop single-page web applications.
- Enables multiple views in a single application by defining multiple routes in the React application.
How do you implement React routing?
We can implement routing in our React application using this method:
Considering we have the components App, About, and Contact in our application:
How do you style React components?
There are several ways in which we can style React components:
- Inline Styling
- JavaScript Object
- CSS Stylesheet
Advance React JS Interview Question
Explain the use of CSS modules in React.
- The CSS module file is created with the .module.css extension
- The CSS inside a module file is available only for the component that imported it, so there are no naming conflicts while styling the components.
Differentiate between Real DOM and Virtual DOM.
Real DOM | Virtual DOM |
---|---|
1. It updates slow. | 1. It updates faster. |
2. Can directly update HTML. | 2. Can’t directly update HTML. |
3. Creates a new DOM if element updates. | 3. Updates the JSX if element updates. |
4. DOM manipulation is very expensive. | 4. DOM manipulation is very easy. |
5. Too much of memory wastage. | 5. No memory wastage. |
List some of the major advantages of React.
Some of the major advantages of React are:
- It increases the application’s performance
- It can be conveniently used on the client as well as server side
- Because of JSX, code’s readability increases
- React is easy to integrate with other frameworks like Meteor, Angular, etc
- Using React, writing UI test cases become extremely easy
React JS Interview Question
What are the limitations of React?
Limitations of React are listed below:
- React is just a library, not a full-blown framework
- Its library is very large and takes time to understand
- It can be little difficult for the novice programmers to understand
- Coding gets complex as it uses inline templating and JSX
What do you understand by Virtual DOM? Explain its working.
A virtual DOM is a lightweight JavaScript object which originally is just the copy of the real DOM. It is a node tree that lists the elements, their attributes and content as Objects and their properties. React’s render function creates a node tree out of the React components. It then updates this tree in response to the mutations in the data model which is caused by various actions done by the user or by the system.
This Virtual DOM works in three simple steps.
- Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representation.
- Then the difference between the previous DOM representation and the new one is calculated.
- Once the calculations are done, the real DOM will be updated with only the things that have actually changed.
What is a state in React and how is it used?
States are the heart of React components. States are the source of data and must be kept as simple as possible. Basically, states are the objects which determine components rendering and behavior. They are mutable unlike the props and create dynamic and interactive components. They are accessed via this. State().
Advance React JS Interview Question
Differentiate between state full and stateless components.
Stateful Component | Stateless Component |
---|---|
1. Stores info about component’s state change in memory | 1. Calculates the internal state of the components |
2. Have authority to change state | 2. Do not have the authority to change state |
3. Contains the knowledge of past, current and possible future changes in state | 3. Contains no knowledge of past, current and possible future state changes |
4. Stateless components notify them about the requirement of the state change, then they send down the props to them. | 4. They receive the props from the Stateful components and treat them as callback functions. |
List some of the cases when you should use Refs.
Following are the cases when refs should be used:
- When you need to manage focus, select text or media playback
- To trigger imperative animations
- Integrate with third-party DOM libraries