React JS interview questions for experienced/React JS Interview Questions and Answers for Freshers & Experienced

What is the Current Stable Version of React?

The current stable version of React is version 17.5

Can JSX element be attached to other JSX components?

Yes, you can use attach JSX element with other JSX components which is very much similar to nesting HTML elements.

Why do you need to use props.children?

This props.children allow you to pass a component as data to other components.

How to redirect to another page in react js?

The best way to redirect a page in React.js depends on what is your use case. Let us get a bit in detail:

If you want to protect your route from unauthorized access, use the component and try this:

Example:

import React from 'react'

import { Redirect } from 'react-router-dom'

const ProtectedComponent = () => {

if (authFails)

return <Redirect to='/login' />

}

return <div> My Protected Component </div>

}

How to reload the current page in react js?

Reloading/Refreshing a page using Javascript:
Use Vanilla JS to call the reload method for the specific page using the following code:

window.location.reload(false);

How to link one page to another page in react js?

There are two ways to link one page to another to React:

Using React Router: Use the feature from the react-router to link the first page to the second one.

<Link to ='/href' ></Link>

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 useState and useEffect calls.

* You should call hooks from React functions only. Don't call hooks from regular JavaScript functions.

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.

Why do we need a Router in React?

React Router plays an important role to display multiple views in a single page application. It is used to define multiple routes in the app. When a user types a specific URL into the browser, and if this URL path matches any 'route' inside the router file, the user will be redirected to that particular Route. So, we need to add a Router library to the React app, which allows creating multiple routes with each leading to us a unique view.

<switch>
<h1>React Router Example</h1>
<Route path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</switch>

What are Forward Refs?

Ref forwarding is a feature which is used for passing a ref through a component to one of its child components. It can be performed by making use of the React.forwardRef() method. It is particularly useful with higher-order components and specially used in reusable component libraries.

Example-

import React, { Component } from 'react';
import { render } from 'react-dom';

const TextInput = React.forwardRef((props, ref) => (
<input type="text" placeholder="Hello World" ref={ref} />
));

const inputRef = React.createRef();

class CustomTextInput extends React.Component {
handleSubmit = e => {
e.preventDefault();
console.log(inputRef.current.value);
};
render() {
return (
<div>
<form onSubmit={e => this.handleSubmit(e)}>
<TextInput ref={inputRef} />
<button>Submit</button>
</form>
</div>
);
}
}
export default App;

Is it possible for a web browser to read JSX directly?

Web browsers can't read JSX directly. This is because the web browsers are built to read the regular JS objects only, and JSX is not a regular JavaScript object.

If you want a web browser to read a JSX file, you must transform the files into a regular JavaScript object. For this purpose, Babel is used.

When do we prefer to use a class component over a function component?

If a component needs state or lifecycle methods, we should use the class component; otherwise, use the function component. However, after React 16.8, with the addition of Hooks, you could use state, lifecycle methods, and other features that were only available in the class component right in your function component.

How can you create a component in React?

There are two possible ways to create a component in React:

Function Components: This is the simplest way to create a component in React. These are the pure JavaScript functions that accept props object as the first parameter and return React elements:

function Greeting({ message }) {
return <h1>{`Hello, ${message}`}</h1>
}
Class Components: The class components method facilitates you to use ES6 class to define a component. The above function component can be written as:

class Greeting extends React.Component {
render() {
return <h1>{`Hello, ${this.props.message}`}</h1>
}
}

How to apply validation on props in React?

Props validation is a tool which helps the developers to avoid future bugs and problems. It makes your code more readable. React components used special property PropTypes that help you to catch bugs by validating data types of values passed through props, although it is not necessary to define components with propTypes.

We can apply validation on props using App.propTypes in React component. When some of the props are passed with an invalid type, you will get the warnings on JavaScript console. After specifying the validation patterns, you need to set the App.defaultProps.

class App extends React.Component {
render() {}
}
Component.propTypes = { /*Definition */};

Why is switch keyword used in React Router v4?

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.

What is the significance of Store in Redux?

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 the 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.

Explain the role of Reducer.

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 the action, and then returns new values. It returns the previous state as it is, if no work needs to be done.

How are Actions defined in 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. Below is an example of Action and Action Creator:

function addTodo(text) {
return {
type: ADD_TODO,
text
}
}

What do you understand by “Single source of truth”?

Redux uses ‘Store’ for storing the application’s entire state at one place. So all the component’s state are stored in the Store and they receive updates from the Store itself. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.

What are the three principles that Redux follows?

* Single source of truth: The state of the entire application is stored in an object/ state tree within a single store. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.

* State is read-only: The only way to change the state is to trigger an action. An action is a plain JS object describing the change. Just like state is the minimal representation of data, the action is the minimal representation of the change to that data.

* Changes are made with pure functions: In order to specify how the state tree is transformed by actions, you need pure functions. Pure functions are those whose return value depends solely on the values of their arguments.

Explain Flux.

Flux is an architectural pattern which enforces the uni-directional data flow. It controls derived data and enables communication between multiple components using a central Store which has authority for all data. Any update in data throughout the application must occur here only. Flux provides stability to the application and reduces run-time errors.

Why is it necessary to start component names with a capital letter?

In React, it is necessary to start component names with a capital letter. If we start the component name with lower case, it will throw an error as an unrecognized tag. It is because, in JSX, lower case tag names are considered as HTML tags.

What is the significance of keys in React?

Keys are used for identifying unique Virtual DOM Elements with their corresponding data driving the UI. They help React to optimize the rendering by recycling all the existing elements in the DOM. These keys must be a unique number or string, using which React just reorders the elements instead of re-rendering them. This leads to increase in application’s performance.

What are Pure Components?

Pure components are the simplest and fastest components which can be written. They can replace any component which only has a render(). These components enhance the simplicity of the code and performance of the application.

What can you do with HOC?

HOC can be used for many tasks like:

* Code reuse, logic and bootstrap abstraction
* Render High jacking
* State abstraction and manipulation
* Props manipulation

Is it easier to learn React Native after ReactJs?

Yes, after learning ReactJS, it becomes easier to learn React Native. React Native is an open-source mobile application framework that is used to develop applications for Android, iOS, Web, and UWP. Furthermore, with the knowledge of React Native, you can easily switch to mobile app development.

What are the prerequisites for learning React?

The following are the prerequisites to learn React: Basic knowledge of HTML, CSS, and JavaScript ES5. Basic understanding of JavaScript ES6 features.

Is ReactJS easy to learn?

React JS is known to have an easier learning curve as compared to other libraries, like Angular and Node JS. Those who already know JavaScript, won’t have to spend much time learning React JS. It usually takes around 4 to 5 days to learn React Js basics, depending on your learning capabilities.

What is the use of ReactJS?

React JS is used to develop high-performing, dynamic, and responsive UI for web interfaces. It is also used for handling the view layer for web applications.

What skills are needed to become a successful React JS Developer?

To become a successful React JS developer, you must develop technical skills, such as knowledge of JavaScript, HTML, CSS; basic understanding of JavaScript ES6 features, and beyond; and understanding of React.js and its core principles. In addition to these technical skills, you need to have good people skills and interpersonal skills.

What are Styled Components?

Styled Components is an open-source CSS-in-JS library that bridges the gap between components and styling. It is the successor of CSS Modules. Styled components are a way to write CSS that’s scoped to a single component and cannot leak to any other element in the page. It allows users to write plain CSS in their components without worrying about class name collisions.

The Styled Components provides:

1. Automatic critical CSS
2. Easier deletion of CSS
3. No class name bugs
4. Dynamic and intuitive styling

How many ways can we style the React Component?

There are four ways to style React Component:

1. Inline Styling
2. CSS Module
3. Styled Components
4. CSS Stylesheet

What is CSS Module styling in React?

CSS Module is a CSS file but with a key difference. Every class name and animation inside a CSS module is by default scoped locally to the component that is importing it. It is available only for the component which imports it and cannot be applied to any other components without your permission. It means that one can use virtually any valid name for the classes, without worrying about conflicts with other class names in the application. You can create a CSS Module file with the .module.css extension.

What do you mean by Component Driven Development (CDD)?

Component Driven Development (CDD) is a methodology that holds the developing process which is revolving around the components. It is a process that creates UIs from the bottom up by starting at the components level and ending at the pages or screen level. It is a concept that applies to pattern libraries, design systems, and modern JavaScript frameworks.

Explain the use of the ScrollView component.

The ScrollView component is a generic scrolling container. It can contain multiple components and views. However, the scrollable items need not be homogeneous. It enables you to scroll both vertically and horizontally by setting the horizontal property.

Explain the use of Flexbox in React Native?

Flexbox is a layout implementation in React Native. It offers an efficient way to create UIs and control positioning in React Native. It provides 3 properties, namely flexDirection, justifyContent, and alignItems to achieve the desired layout.

How do you modularize code in React?

We can modularize code by using the export and import properties. They help in writing the components separately in different files.

//ChildComponent.jsx
export default class ChildComponent extends React.Component {
render() {
return(

<div>

<h1>This is a child component</h1>

</div>

);
}
}

//ParentComponent.jsx
import ChildComponent from './childcomponent.js';
class ParentComponent extends React.Component {
render() {
return(

<div>
<App />
</div>

);
}
}

List some of the cases when you should use Refs.

Following are the cases when refs should be used:

1. When you need to manage focus, select text or media playback
2. To trigger imperative animations
3. Integrate with third-party DOM libraries

How are Actions defined in Redux?

Actions are plain JavaScript objects that have a type field. Actions must have a type property that indicates the type of Action being performed. They must be defined as a String constant and allow you to add more properties to it. We can create actions using the functions called Action Creators.

Example:

function addTodo(text) {

return {

type: ADD_TODO,

text

}

}

What is the use of Reducer?

Reducers are pure functions that describe how the state of the application changes when an action is triggered. Reducers take the previous state and action and then return a new state.

In simple terms, if you repeat the same test with the same input as arguments, you can always expect the same output.

What do you understand by refs in React?

Refs is the short hand for References in React. It is an attribute which helps to store a reference to a particular React element or component, which will be returned by the components render configuration function. It is used to return references to a particular element or component returned by render(). They come in handy when we need DOM measurements or to add methods to the components.

class ReferenceDemo extends React.Component{
display() {
const name = this.inputDemo.value;
document.getElementById('disp').innerHTML = name;
}
render() {
return(

<div>
Name: <input type="text" ref={input => this.inputDemo = input} />
<button name="Click" onClick={this.display}>Click</button>

<h2>Hello <span id="disp"></span> !!!</h2>

</div>
);
}
}

What are synthetic events in React?

Synthetic events are the objects which act as a cross-browser wrapper around the browser’s native event. They combine the behavior of different browsers into one API. This is done to make sure that the events show consistent properties across different browsers.

Explain the lifecycle methods of React components in detail.

Some of the most important lifecycle methods are:

1. componentWillMount() – Executed just before rendering takes place both on the client as well as server-side.

2. componentDidMount() – Executed on the client side only after the first render.

3. componentWillReceiveProps() – Invoked as soon as the props are received from the parent class and before another render is called.

4. shouldComponentUpdate() – Returns true or false value based on certain conditions. If you want your component to update, return true else return false. By default, it returns false.

5. componentWillUpdate() – Called just before rendering takes place in the DOM.

6. componentDidUpdate() – Called immediately after rendering takes place.

7. componentWillUnmount() – Called after the component is unmounted from the DOM. It is used to clear up the memory spaces.

What are the different phases of React component’s lifecycle?

There are three different phases of React component’s lifecycle:

* Initial Rendering Phase: This is the phase when the component is about to start its life journey and make its way to the DOM.

* Updating Phase: Once the component gets added to the DOM, it can potentially update and re-render only when a prop or state change occurs. That happens only in this phase.

* Unmounting Phase: This is the final phase of a component’s life cycle in which the component is destroyed and removed from the DOM.


In case you are facing any challenges with these React interview questions, please comment on your problems in the section below.

What are the three fundamental principles of Redux?

The three fundamental principles of Redux are:

1. Single source of truth. It means that the state of your application is stored in an object tree within a single store. The single state tree will make it easier to make changes and inspect the application.
2. State is read-only. It means that the only way to change the state is to trigger an action.
3. Changes are made with pure functions. You need pure functions to specify how the state tree is transformed by actions.

What is arrow function in React? How is it used?

Arrow functions are more of brief syntax for writing the function expression. They are also called ‘fat arrow‘ (=>) the functions. These functions allow to bind the context of the components properly since in ES6 auto binding is not available by default. Arrow functions are mostly useful while working with the higher order functions.

//General way
render() {
return(
<MyInput onChange={this.handleChange.bind(this) } />
);
}
//With Arrow Function
render() {
return(
<MyInput onChange={ (e) => this.handleOnChange(e) } />
);
}

“In React, everything is a component.” Explain.

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.

What is the second argument that can optionally be passed to setState and what is its purpose?

A callback function which will be invoked when setState has finished and the component is re-rendered.
Since the setState is asynchronous, which is why it takes in a second callback function. With this function, we can do what we want immediately after state has been updated.

What is React.cloneElement? And the difference with this.props.children?

React.cloneElement clone and return a new React element using using the passed element as the starting point. The resulting element will have the original element's props with the new props merged in shallowly. New children will replace existing children. key and ref from the original element will be preserved.

React.cloneElement only works if our child is a single React element. For almost everything {this.props.children} is the better solution. Cloning is useful in some more advanced scenarios, where a parent send in an element and the child component needs to change some props on that element or add things like ref for accessing the actual DOM element.

Explain the components of Redux.

Redux is composed of the following components:

Action — Actions are payloads of information that send data from our application to our store. They are the only source of information for the store. We send them to the store using store.dispatch(). Primarly, they are just an object describes what happened in our app.

Reducer — Reducers specify how the application’s state changes in response to actions sent to the store. Remember that actions only describe what happened, but don’t describe how the application’s state changes. So this place determines how state will change to an action.

Store — The Store is the object that brings Action and Reducer together. The store has the following responsibilities: Holds application state; Allows access to state via getState(); Allows state to be updated via dispatch(action); Registers listeners via subscribe(listener); Handles unregistering of listeners via the function returned by subscribe(listener).

It’s important to note that we’ll only have a single store in a Redux application. When we want to split your data handling logic, we’ll use reducer composition instead of many stores.

Search
R4R Team
R4R provides React JS Freshers questions and answers (React JS Interview Questions and Answers) .The questions on R4R.in website is done by expert team! Mock Tests and Practice Papers for prepare yourself.. Mock Tests, Practice Papers,React JS interview questions for experienced,React JS Freshers & Experienced Interview Questions and Answers,React JS Objetive choice questions and answers,React JS Multiple choice questions and answers,React JS objective, React JS questions , React JS answers,React JS MCQs questions and answers Java, C ,C++, ASP, ASP.net C# ,Struts ,Questions & Answer, Struts2, Ajax, Hibernate, Swing ,JSP , Servlet, J2EE ,Core Java ,Stping, VC++, HTML, DHTML, JAVASCRIPT, VB ,CSS, interview ,questions, and answers, for,experienced, and fresher R4r provides Python,General knowledge(GK),Computer,PHP,SQL,Java,JSP,Android,CSS,Hibernate,Servlets,Spring etc Interview tips for Freshers and Experienced for React JS fresher interview questions ,React JS Experienced interview questions,React JS fresher interview questions and answers ,React JS Experienced interview questions and answers,tricky React JS queries for interview pdf,complex React JS for practice with answers,React JS for practice with answers You can search job and get offer latters by studing r4r.in .learn in easy ways .