React.js

ReactJS Interview Questions and Answers

In this post, we feature a comprehensive article on the most important ReactJS Interview Questions. There is no need to worry for your next interview test, because Java Code Geeks are here for you!

I will present a list of ReactJS interview questions and their answers. The article flows from the basic concepts moving all the way up to advanced topics. The article gives an insight into ReactJS enabling you to clear that interview for ReactJS developer position. The content will help you make an impression and solid claim as a ReactJS developer. Let us get started without further delay!

1. Getting Started with ReactJS

1.1 How would you use ReactJS in an existing Web page?

According to ReactJS website

…we can use as much or as little of it as we need…

What that means is, we can have just a few React Components in a page. Or we can create a full blown React powered App. The choice is ours and depends on the requirement at hand. In this case, we can use the React Library with a couple of script tags in our application like below:

01
02
03
04
05
06
07
08
09
10
11
12
<html>
<head>
    <script src="https://unpkg.com/react@16/umd/react.production.js"        
    crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.js"
    crossorigin></script>
    <!-- Load our React component. -->
    <script src="my_component.js"></script>
</head>
<body></body>
</html>

Next, we need to use the id of the container div element in React code like below:

And that’s all we need to do, to display our React Component in an existing Web page.

ReactDOM.render("react element",
    document.getElementById("id of the container"));

1.2 What all does one need to create a full blown React Application?

We need a few tools to assemble our app. Commonly, following set of tools should suffice to build a tool chain to create a Single Page React Application:

  1. Node v10.15.3 or above
    Node is JavaScript that runs on the server side.
  2. npm v6.4.1 or above
    npm comes along with the installer for Node available at Nodejs.org.
  3. Visual Studio Code IDE
    This is a matter of personal preference and with my background in technologies and tools, this is my preferred IDE. Although one can choose from a whole host of IDEs and text editors available out there, both free and for a premium.
  4. create-react-app
    We can use create-react-app post the installation of Node using the npm tool as below:
>npm install -g create-react-app  
>create-react-app app .\ 

It creates a directory named app and places the artifacts of our React application in it. Alternatively we can use the npx tool to download a temporary copy of create-react-app package and use it. Once done using it the package is discarded. This prevents polluting the global namespace with less frequently used tools.

>npx create-react-app my-app

To use JSX that compiles on the server. We need to follow additional steps to add Babel to our tool chain. The steps for the same are as follows:

-->Run the below two steps at the root of the project
>npm init -y
>npm install babel-cli@6 babel-preset-react-app@3

-->Now we need to add below step to our build script
>npx babel src --out-dir build --presets react-app/prod

1.3 What about the learning curve with ReactJS?

From beginners to seasoned developers, it does not take a lot of time to get up to speed with React. Ranging from a day or two to a week should be enough to be productive with React. Off course, I am assuming a certain level of proficiency with other technologies including HTML, JavaScript and CSS. The learning curve in this case is not too steep even for developers completely new to React.

1.4 How does React fit into the front end Stack/Architecture?

React plays the role of the V in MVC architecture on the front-end. MVC as we know stands for Model-View-Controller architecture. With roles of each clearly defined and assigned. Model is the data source for our front end and Controller syncs the Model with its presentation, i.e. View. It is the View where we use the React Library, but we still need to rely on other Frameworks or libraries to fill in the other two roles.

1.5 Is React a library or a Framework and why?

React is a library in that it does not force upon an opinionated way of building the front end architecture. Remember that we can use it only as much as we want or need to. This allows us the freedom to build the other artifacts using whatever technology or framework we choose. Thus it is more of a library, a collection of functions, rather than a specification or set of rules on how to build each component of MVC for the front-end. With that said React in a sentence can be described as:

React is a declarative, component based and unassuming JavaScript library.

To dig deep into the above, React is

Declarative, in that, we just need to tell React what we want to see on the UI without getting bogged down in implementation details. We do not need to provide or write step by step code to build the View. React knows how to go about it’s role and just needs concise instructions on what is needed.

Is Component based, instead of splitting UI templates, code to handle UI events, code to communicate with server and update the UI, into separate pieces. React composes components where the UI and code to manage it are all packed into a single Component.

Is unassuming by nature since it makes no supposition about other tools and frameworks that you may want or need to use along side it. It works just as well with and without much else too. Moreover it has server side rendering capabilities as well, in a Node.js environment of course.

1.6 How compatible is React with other Tools and Frameworks?

When it comes to compatibility, React is just the right tool. Because it does its job well and can work along with any other library or tool or framework without getting in their way. Like previously stated it fulfills the role of V or View in an MVC based front-end architecture. We most likely use other tools and frameworks to do the job of the M or Model and C or Controller. The way React is built to work allows for usage of other technologies and as such there is little hindrance with their use along with React.

With that said, any changes to the DOM or UI by other libraries might leave React confused. Since, it is not aware of the changes by other libraries to the View. We need to be careful with using multiple libraries on the front-end for DOM manipulation. There are workarounds if we absolutely need additional libraries in addition to React to manipulate the DOM. But it might unnecessarily complicate matters.

2. ReactJS Concepts

2.1 What are elements?

Elements in React are the objects returned by the React.createElement() calls. For example to display a greeting element in react we would write:

    const element = React.createElement("h2", 
        {...additional attributes for div like css classes 
            and event handlers...},
         "Hello World!");
    ReactDOM.render(element, document.getElementById("root"));

A React Element looks somewhat like below:

{ 
    type: 'html tag name like div or p...',
    props: {
        ...
    }
...
};

We use elements to build our UI, we can think of an element as a description of what we want the UI to look like. They are the smallest unit we deal with in a React Application. They are the objects that a Component is built around to manage it. We create an element by creating a React DOM object. Unlike a browser DOM object these React elements are lightweight. React renders these elements by comparing the React DOM and browser DOM and making only necessary changes. Also, since React elements are immutable, we need to recreate another instance with updated state to make changes to the UI.

2.2 What are Components?

Components are the basic building blocks in React. All UIs built with React are basically composed of a hierarchy of Components. As such, in a React application, we have a root component with a tree of child components with each having child components of their own. In terms of code we can think of each component as a JavaScript function. There are a couple of ways to define components:

function HelloWorld() {
    return <h2>Hello World!</h2>;
}

or using ES6 class we can define a component as

class HelloWorld extends React.Component {   
    constructor(props) {
        super(props);//This is mandatory
        this.state = {...};//Only available in ES6 classes
    } 
    render() {
        return <h2>Hello World!</h2>;
    }
}

A crucial difference between the two approaches is that only components defined as ES6 classes have internal state available to them. Though there is a workaround to this issue. We can use the create-react-class method to define our function component. It is used as below:

var createReactClass = require('create-react-class');
var SayHello = createReactClass({
  render: function() {
    return <h1>Hello, {this.props.name}</h1>;
  }
});

2.3 Describe the different types of Components

There two types of components known as Controlled and Uncontrolled. A controlled component is a technique applied to form elements. We wrap the stateful DOM elements like input, select, radio, checkbox and others as React Components. Since we control their state and changes to it thus such components are called Controlled Components.

We make the React state, as the documents state, the single source of truth. To enable such control over the individual tag we bind its value property to React state and its onchange to React a callback, which in turn, calls setState. Thus we exercise full control over the DOM Form element. The components created thus are referred to as Controlled Components.

2.4 What is meant by “lifting state up” in React?

This relates to sharing of data or rather state among two or more components. These components could be multiple instances of the same type or different types. In React we move state which is to be shared to a common ancestor of such components higher up the hierarchy. Since we essentially moving state higher up in the hierarchy from components that consume it. So, it is referred to as “lifting state up”. An example of such a situation could be as below.

2.5 Elaborate on ReactJS data binding capabilities

In every React application we have a hierarchy of components. The data flow is from Parent Component to a Child or descendant Components using props, which stands for properties.

2.6 What is JSX? and is it mandatory for ReactJS Development?

JSX stands for JavaScript XML. It adds syntactic sugar and makes our code look a lot more elegant. It allows us to write JavaScript that looks like XML/HTML. But more importantly, the primary purpose is to enable creating HTML of complex components in an easy and simple manner. We can even embed JavaScript expressions in JSX in curly braces. Though by using JSX syntax an additional trans piling stage is added, where in, JSX is converted into equivalent JavaScript.

It is not mandatory to use JSX when developing with React. But once one realizes the power it bestows, would prefer it over the other approach of using the createElement API. It allows us to visualize our UI rendering code in terms of components as opposed to DOM elements. An example of using JSX is as below:

    const greetUser = <h1>Welcome</h1>;
    ReactDOM.render(greetUser, document.getElementById("root"));

2.7 Describe React Component life cycle

A component goes through various states during it’s life cycle. We listen to various events triggered as a result of this change between states. The common ones in the life cycle can be summarized as:

Application Startup
  1. constructor()
  2. render()
  3. componentDidMount()

This is followed by Iterations of below when the component or ones higher up in the hierarchy is updated as the application runs

Update Cycle

  1. shouldComponentUpdate()
  2. render()
  3. componentDidUpdate()


As the application is shutting down following life cycle events occur

Application Shutdown
  1. componentDidUnmount()

2.8 What are pure functions?

As we know, data flows down the hierarchy of components. Each component receives a single props parameter with data contained there in. Reactjs expects that the data passed to a component as props should not be altered in any way. In essence, Components should treat the data in the props objects passed to them as ready-only.

2.9 How ReactJS application manages state?

State management uses state property which is similar to the props that is passed down the component hierarchy. With the exception, that each component has a private state that it manages by itself. To enable state management with React we must use the ES6 classes to implement our components. We can initialize state in constructor and update it using the setState method elsewhere. A example of a component using ES6 and state looks like below:

class HelloWorld extends React.Component {
    constructor(props) {
        super(props);
        this.state = ({ greeting: "Hello World!" });
    }
    render() {
        return (<div>{this.state.greeting}</div>);
    }
}

2.10 Can we choose between ES5 and ES6 with React?

Yes we can use either one for React development but would favor ES6 over ES5. If you are familiar and comfortable with one of them you are all set to use the same with React. Although, ES6 being newer would be a favorite to start on any new projects. The differences when using ES5 or ES6 with React are as seen in the below code snippets:

2.11 What is Unidirectional data flow?

The data flows down from the root to the leaf components. It is referred to as Unidirectional data binding. Each component can choose to share additional data with the downstream components and add the same to the props. Although the state of the component is private to the component, it can share the same with components down the order if it so chooses. Since the data is flowing in a single direction, from components higher up in the hierarchy to those below, it is referred to as Unidirectional or top-down data flow.

2.12 How do you validate user input in ReactJS?

We use controlled components in React to validate user input. The approach binds to the onChange event and the value attribute of the Form Controls. And thus receive notification, with every keystroke, of changes in the value of the control. This enables handling validation of user input. The below example further clarifies the technique.

class ValidationDemo {
    constructor(props) {
        super(props);
        this.state = { name: "Siddharth" };
    }
    handleChange = (e) => {
        // validation code can reside here
        this.state.setState({ name: e.target.value });
    }
    render() {
        return <input value={this.state.name} onChange={this.handleChange}/>;
    }

2.13 What does the term Virtual DOM mean?

React maintains a copy of the UI or DOM in an object referred to as Virtual DOM. This is lightweight and React maintains synchronization between the Virtual DOM and browser DOM. The process is called Reconciliation and ReactDOM is incharge of effecting the required changes.

3. Advanced ReactJS

3.1 What are React Fragments?

React fragments allow us to return multiple components without the need for additional nodes to group them together. For example take a look at the below example where a component renders two elements:

function Greetings() {
    return <div>
           <Greetings />
           <Login></Login>
           </div>;
}

As you can see we had to wrap the returned components with a div tag which is quite unnecessary. To work around this we can use React Fragments to wrap multiple components without adding additional tags like below:

function Greetings() {
    return <React.Fragment>
           <Greetings />
           <Login></Login>
           </React.Fragment>;
}

3.2 What about Accessibility support in React?

In React all of the HTML aria-* attributes are supported in JSX and can appear just as they do in plain HTML. Meaning in hyphen-case or kebab-case or Lisp-case. An example of it is as follows:

class UserForm extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return <form>
               <label id="label">Name:</label>
               <input aria-required="true" aria-labelledby="label" type="text" />
               </form>;
    }
}

3.3 What are Higher Order Components?

This is not an integral concept rather a way or pattern used in React. Higher Order Components take as input a component and return as output an enhanced component. This is another example of the com positional nature of React at work. In advanced scenarios like implementation of cross cutting concerns, these prove to be quite useful.

3.4 How do Events work in ReactJS?

Event Handling in React is pretty similar to the way DOM event handling is done. Though there are a few differences. Firstly, event names are in camel case as opposed to the DOM events which are in lower case. Another difference is that return false; does not stop event propagation. In React, we need to explicitly call e.preventDefault() to achieve the same. We specify event handlers as either string when not using JSX. But with JSX we need to specify methods.

With JSX we can either specify a method or use arrow function syntax. But we need to bind these event handlers to get predictable behavior with regards to this. We can achieve this by binding in the constructor of our Component like so:

//Adding event handler using JSX
...
class Button extends React.Component {
    constructor(props) {
        super(props);
        this.handleClick.bind(this);
    }
    handleClick(e) {
        console.log("I was clicked");
    }
    render() {
        return (<button>
               Click Me!</button>);
    }
}
ReactDOM.render(Button, document.getElementById("root"));
...

3.5 What are Refs in ReactJS?

Refs are a way to access DOM elements or user defined elements created and rendered in the render method. The use of Refs should be an exception rather than the norm. With that said specific use cases necessitate the use of refs for implementing certain functionalities. For example if we want to switch focus to an input on the click of a button we would need to get a reference to the input to implement the same. An implementation of such a feature using refs could be as below:

class NamePrompt extends React.Component {
    constructor(props) {
        super(props);
        this.inputRef = React.createRef();
    }
    handleClick = (e) = {
        this.inputRef.current.focus();
    }
    render() {
    return <React.Fragment>
           <input type="text" ref={this.inputRef} />
           <input type="button" onClick={handleClick} />
           </React.Fragment>;
    }
}

Refs feature is available to class components alone and as such cannot be used with function components. It is so because function components do not have instances. To use refs with such components we need to convert then to class components.

4. Download the Source Code

Download
You can download the full source code of this example here: ReactJS Interview Questions and Answers

5. Conclusion

This is a summary of some of the most important concepts and terminologies used in ReactJS. These questions have been answered with the aim to make you feel ready.

If you enjoyed this, then subscribe to our newsletter to enjoy weekly updates and complimentary whitepapers! Also, check out our courses for more advanced training!

You are welcome to contribute with your comments and we will include them in the article!

Siddharth Seth

Siddharth is a Software Development Professional with a Master degree in Computer Applications from IGNOU. He has over 14 years of experience. And currently focused on Software Architecture, Cloud Computing, JavaScript Frameworks for Client and Server, Business Intelligence.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Peter
Peter
4 years ago

Good choice of topics, but bad examples of interview questions. Most interviewers will not ask so many theoretical questions. They’ll give you practical coding tasks that require you to apply your knowledge. For example like the tasks on this React test: https://www.testdome.com/tests/react-js-online-test/104

Sana
Sana
2 years ago

I’m preparing for a reactjs interview but could not find a good article. However, your article has helped me a lot and i also found a content of reactjs interview questions which has good set of questions, probably this can help the readers in clearing interviews too.

Back to top button