A list of top frequently asked ReactJS interview questions and answers are given below.
React is a front-end library developed by Facebook. It is used for handling the view layer for web and mobile apps. ReactJS allows us to create reusable UI components. It is currently one of the most popular JavaScript libraries and has a strong foundation and large community behind it.
React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It lets you compose complex UIs from small and isolated pieces of code called “components”.
There are reason to use ReactJS
render() function is used to update the UI. For this, you have to create a new element and send it to ReactDOM.render(). React elements are immutable and once you create an element, you cannot change its attributes. Thus, elements are like a single frame and it depicts the UI at some point. ReactDOM.render() controls the content of the container node you pass and if there is any DOM element already present in it then it would be replaced when first called.
The ref is used to return a reference to your element. Refs should be avoided in most cases but they can be useful when you need DOM measurements or to add methods to your components.
React keys are useful when working with dynamically created components or when your lists are altered by users. Setting the key value will keep your components uniquely identified after the change.
render () {{"{"}}
return (
<ul>
{{"{"}}this.state.todoItems.map(({{"{"}}task, uid}) => {{"{"}}
return <li key={{"{"}}uid}>{{"{"}}task}</li>
})}
</ul>
)
}
Arrow functions are extremely important for React operations. It prevents this bugs. Arrow functions make it easier to predict the behavior of this bugs when passed as callbacks. They don’t redefine the value of this within their function body. Hence, prevents bugs caused by the use of this within callbacks.
Javascript- is a dynamic computer programming language. It is lightweight and most commonly used as a part of web pages, whose implementations allow client-side script to interact with the user and make dynamic pages. It is an interpreted programming language with object-oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of the excitement being generated by Java. JavaScript made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers.
Client-side JavaScript is the most common form of the language. The script should be included in or referenced by an HTML document for the code to be interpreted by the browser.
AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.
AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.
React– React was developed by Facebook in March 2013. It is a JavaScript library that is used for building user interfaces. React creates large web applications and also provides speed, scalability, and simplicity.
VueJs- Launched in February 2014, Vue is the most famous and rapidly growing framework in JS field. Vue is an intuitive, fast and composable MVVM for building interactive interfaces. It is extremely adaptable and several JavaScript libraries make use of this. Vue is also a web application framework that helps in making advanced single page applications.
Examples of JSX elements with the attributes:
<a href="http://www.yahoo.com">Welcome to the Yahoo</a>;
var title = <h1 id="title">Introduction to React.js: Part I</h1>;
Some of the major advantages of React are:
Limitations of React are listed below:
JSX is a shorthand for JavaScript XML. This is a type of file used by React which utilizes the expressiveness of JavaScript along with HTML like template syntax. This makes the HTML file really easy to understand. This file makes applications robust and boosts its performance. Below is an example of JSX:
render(){{"{"}} return( <div> <h1>Welcome ToTekslate!!</h1> </div> ); }
If your component has state or a lifecycle method(s), use a Class component. Otherwise, use a Functional component.
In React, for every DOM object, there is a corresponding "virtual DOM object." A virtual DOM object is a representation of a DOM object, like a lightweight copy.
A virtual DOM object has the same properties as a real DOM object, but it lacks the real thing's power to directly change what's on the screen.
Manipulating the DOM is slow. Manipulating the virtual DOM is much faster, because nothing gets drawn onscreen. Think of manipulating the virtual DOM as editing a blueprint, as opposed to moving rooms in an actual house.
Real DOM and Virtual DOM
Real DOM | Virtual DOM |
It updates slowly. | It updates faster. |
Can directly update HTML. | Can’t directly update HTML. |
Creates a new DOM if element updates. | Updates the JSX if element updates. |
DOM manipulation is very expensive. | DOM manipulation is very easy. |
Too much of memory wastage. | No memory wastage. |
TOPIC | REACT | ANGULAR |
ARCHITECTURE | Only the View of MVC | Complete MVC |
RENDERING | Server side rendering | Client side rendering |
DOM | Uses virtual DOM | Uses real DOM |
DATA BINDING | One-way data binding | Two-way data binding |
DEBUGGING | Compile time debugging | Run time debugging |
AUTHOR |
Components are the building blocks of a React application’s UI. These components split up the entire UI into small independent and reusable pieces. Then it renders each of these components independent of each other without affecting the rest of the UI
In order to ensure events have consistent properties across different browsers, React wraps the browser's native events into "synthetic events", consolidating browser behaviors into one API. Synthetic events are a cross-browser wrapper around the browser's native event system.
Each React component must have a render() compulsory. If more than one HTML elements needs to be rendered, then they must be grouped together inside one enclosing tag such as <form>, <group>,<div> etc. It returns to the single react element which is the presentation of native DOM Component. This function must be kept pure i.e., it must return the same result each time it is invoked.
Props are shorthand for Properties in React. They are read-only components which must be kept pure i.e. immutable. They are always passed down from the parent to the child components throughout the application. A child component can never send a prop back to the parent component. This help in maintaining the unidirectional data flow and are generally used to render the dynamically generated data.
Functional components are just JavaScript functions. They take in an optional input which, as I've mentioned earlier, is what we call props.
Some developers prefer to use the new ES6 arrow functions for defining components.
Arrow functions are more compact and offer a concise syntax for writing function expressions.
By using an arrow function, we can skip the use of two keywords, function
and return
, and a pair of curly brackets. With the new syntax, you can define a component in a single line like this.
1 | const Hello = ({{"{"}} name }) => (<div>Hello, {{"{"}}name}!</div>); |
Class components offer more features, and with more features comes more baggage. The primary reason to choose class components over functional components is that they can have state
.
There are two ways that you can create a class component. The traditional way is to use React.createClass()
. ES6 introduced a syntax sugar that allows you to write classes that extend React.Component
. However, both the methods are meant to do the same thing.
Class components can exist without state too. Here is an example of a class component that accepts an input props and renders JSX.
class Hello extends React.Component {{"{"}} constructor(props) {{"{"}} super (props); } render() {{"{"}} return ( <div> Hello {{"{"}}props} </div> ) } } |
"State" is the heart of any react component, it's an object that determines how that component behaves. In React.js, "state" allows us to create dynamic and interactive components.
Let’s understand the concept of React states with the help of an example:
When a React component initializes, you can set an initial state by defining a method called getInitialState that returns your desired state object:
getInitialState: function() {{"{"}}
return {{"{"}}
currentscore: 60
};
}
render: function() {{"{"}}
// empty variable that will hold either "Winner", "Loser", or “Draw"
var result;
// If score is below 32, it's a loser
if (this.state.currentscore <= 32) {{"{"}}
result = 'Loser';
// if score is on/above 200, it's a winner
} else if (this.state.currentscore >= 200) {{"{"}}
result = 'winner';
// otherwise it's just a draw
} else {{"{"}}
result = 'Draw';
}
return (
<div>
<p>At {{"{"}} this.state.score }, the outcome is "{{"{"}} result }" .</p>
</div>
);
}
In case of Dynamic apps the data needs to be passed around its system. The data in React happens mainly among its components and the external services providing the original data.
After their creation, most components can be customized, using different parameters. These creation parameters are called props.Props are immutable and dumb which means they can only be passed from parent components down and cannot be changed.On initializing React, we define an initial state and keep the state in sync with the props. Once the state is updated, the props can then be easily kept in sync.
Conditions | State | Props |
1. Receive initial value from parent component | Yes | Yes |
2. Parent component can change value | No | Yes |
3. Set default values inside component | Yes | Yes |
4. Changes inside component | Yes | No |
5. Set initial value for child components | Yes | Yes |
6. Changes inside child components | No | Yes |
MVC is easy to manage in a simple application, with few models/controllers. But we can easily start to witness problems as we grow in size with the following problems:
There is a need when models/controllers communicate with each other (through a service layer probably), and these modules changes the states of each others, and the more controllers, the more easy to lose control of who changed the state of a controller.
Asynchronous network calls to retrieve data add the uncertainty of when the model will be changed or modified, and imagine the user changing the UI while a callback from asynchronous call come back, then we will have “non-deterministic” status of the UI.
Change state/model has another layer of complexity which is the mutation. So, when should we consider the state or model is changed and how to build tools to help recognize the mutation? Adding to that if the application is a collaborative applications, (like google docs for examples) where lots of data changes happening in real-time.
There is no way to do undo (travel back in time) easily without adding so much extra code.
We can summarize the above as: “There is no single source of truth of the applications at any given time.”, and at any given time we cannot know how the UI will be, and this creates non-determinism UI.
Unidirectional User Interface Architecture
For example there is Flux (Redux is just a variation of Flux).
Redux tries to make: “state mutation predictable”, and it tries to achieve that by the following:
Have one single source of truth (from the state)
States are read only and immutable. Changes are made with pure functions.
Because we use pure functions everywhere, so always the output is deterministic, and we have deterministic UI.
Time Travelling: Because we change the state through actions which are pure JavaScript objects, which means we can, at any moment, re-create the state from scratch if we keep a log of those actions, so time-travelling will be a breath.
Logging actions, we can know who modify the state, and when exactly.
Collaborative programs like (google docs) can be achieved easily by sending Actions on the wire and recreate them there. Easy debugging, by logging all actions on production we can re-create the whole situation.
Deterministic UI, because UI rendering using pure function, and the same input will always generate the same output. Unit test is so easy, because we are testing pure functions for UI and state mutation.
Using Props, states or Stores (Redux)
Actions in React must have a type property that indicates the type of ACTION being performed. They must be defined as a String constant and you can add more properties to it as well. In Redux, actions are created using the functions called Action Creators.
Here's an example action which represents adding a new todo item:
{{"{"}}type: ADD_TODO,text: 'Build my first Redux app'}
Reducers are pure functions which specify how the application’s state changes in response to an ACTION. Reducers work by taking in the previous state and action, and then it returns a new state. It determines what sort of update needs to be done based on the type of action, and then returns new values. It returns the previous state as it is if no work needs to be done.
A store is a JavaScript object which can hold the application’s state and provide a few helper methods to access the state, dispatch actions and register listeners. The entire state/ object tree of an application is saved in a single store. As a result of this, Redux is very simple and predictable. We can pass middleware to the store to handle processing of data as well as to keep a log of various actions that change the state of stores. All the actions return a new state via reducers.
Flux | Redux |
The Store contains state and change logic | Store and change logic are separate |
There are multiple stores | There is only one store |
All the stores are disconnected and flat | Single store with hierarchical reducers |
Has singleton dispatcher | No concept of dispatcher |
React components subscribe to the store | Container components utilize connect |
State is mutable | State is immutable |
React Router is a powerful routing library built on top of React, which helps in adding new screens and flows to the application. This keeps the URL in sync with data that’s being displayed on the web page. It maintains a standardized structure and behavior and is used for developing single page web applications. React Router has a simple API.
Although a <div> is used to encapsulate multiple routes inside the Router. The ‘switch’ keyword is used when you want to display only a single route to be rendered amongst the several defined routes. The <switch> tag when in use matches the typed URL with the defined routes in sequential order. When the first match is found, it renders the specified route. Thereby bypassing the remaining routes.
A Router is used to define multiple routes and when a user types a specific URL, if this URL matches the path of any ‘route’ defined inside the router, then the user is redirected to that particular route. So basically, we need to add a Router library to our app that allows creating multiple routes with each leading to us a unique view.
Install node JS on your system. Click on below link
Open CMD in your system
npm install -g create-react-appcreate-react-app my-appcd my-appnpm start