ReactJS Interview Questions

To put your best foot forward, browse through our top spring boot interview questions and answers. Just spend an hour every day before your interview on these questions. Your next spring boot interview will convert into a sure job offer.

  • 4.5 Rating
  • 10 Question(s)
  • 15 Mins of Read
  • 9643 Reader(s)

Advanced

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function Button(props) {
return (
<button type="submit">{props.label}</button>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Button label="Save" />, rootElement);
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const check = 0; // 0, "", null, undefined
return (
<div className="App">
{ check && <span>Hello</span> }
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

This will render 0 to the browser.
When using conditional rendering using logical && operator 0 is evaluated as number and will be rendered by the browser
How we can avoid rendering 0 in the above case.
We need to make the 0 a Boolean by adding !. Code is given below

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const check = 0; // 0, "", null, undefined
return (
<div className="App">
{ !check && <span>Hello</span> }
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

React router is a commonly used module for routing in React applications.
React router component listens to history changes in React applications. It has a URL mapping to components in it. It renders the corresponding component when a match is found.
Link component is used to navigate around in your application.

Code sample below

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
const App = () => (
<Router>
<>
<Link to="/">Home</Link> <Link to="/page">Page</Link>
<Route exact path="/" component={Home} />
<Route path="/page" component={Page} />
</>
</Router>
)
const Home = () => <h2>Home</h2>;
const Page = () => <h2>Page</h2>;
const rootElement = document.getElementById("root");
ReactDOM.render(<App label="Save" />, rootElement);

How to return multiple components without wrapping using div, HOC or Fragment
Fragments help you return a list of items without adding extra nodes to the DOM.
Return as an Array. This is introduced since React 16

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
return (
[
<p>one</p>,
<p>two</p>
]
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Parent to child – props, context
Child to parent – states, callbacks
Siblings – callback, props, context

import React, { Component } from "react";
import Intl, { IntlProvider } from "./Intl";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends Component {
state = {
language: "en"
};
handleClick = () => {
this.setState({
language: this.state.language === "en" ? "fr" : "en"
});
};
render() {
return (
<div className="App">
<IntlProvider language={this.state.language}>
<p>
<Intl id="hello" /> <Intl id="world" />!
</p>
<p>
<button onClick={this.handleClick}>Toggle Language</button>
</p>
</IntlProvider>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
import React, { createContext } from "react";
const IntlContext = createContext(null);
const IntlProvider = ({ children, language }) => {
const languages = {
en: {
hello: "hello",
world: "world"
},
fr: {
hello: "Bonjour",
world: "monde"
}
};
return (
<IntlContext.Provider value={languages[language]}>
{children}
</IntlContext.Provider>
);
};
const Intl = ({ id }) => (
<IntlContext.Consumer>{value => value[id]}</IntlContext.Consumer>
);
export { IntlProvider };
export default Intl;

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity

The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys

Keys used within arrays should be unique among their siblings. However they don’t need to be globally unique. We can use the same keys when we produce two different arrays

To understand this you need understand how the virtual DOM works in React

The virtual DOM (VDOM) is a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM. This process is called reconciliation.

Each time the underlying data changes in a React app, a new Virtual DOM representation of the user interface is created

Updating browser DOM is as follows

  1. Whenever anything may have changed, the entire UI will be re-rendered in a Virtual DOM representation.
  2. The difference between the previous Virtual DOM representation and the new one will be calculated.
  3. The real DOM will be updated with what has actually changed. This is very much like applying a patch.

Look at the example given below

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
render() {
const numbers = [1,2,3,4,5];
const listItems = numbers.map((number) =>
<li>
{number}
</li>
);
return (
<div className="App">
<h2>Hellow World!!</h2>
<div>{listItems}</div>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

This will throw a warning in console

Warning: Each child in an array or iterator should have a unique "key" prop.

To fix it we should change the arrow function “listItems” to

const listItems = numbers.map((number) =>
<li key={number.toString()}>
{number}
</li>
);

React lets you define components as classes or functions. Components defined as classes currently provide more features To define a React component class, you need to extend React.Component.

class App extends React.Component {
render() {
return (
<div className="App">
<h2>Hellow World!</h2>
</div>
);
}
}

The only method you must define in a React.Component subclass is called render() All the other methods described on this page are optional.

Each component has several “lifecycle methods” that you can override to run code at particular times in the process .

Lifecycle methods can be classified into four.

  1. Mounting
  2. Updating
  3. Unmounting
  4. Error handling

Mounting

Methods are listed in the order of their execution

constructor()

The constructor for a React component is called before it is mounted. When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs.

Typically, in React constructors are only used for two purposes:

  1. Initializing local state by assigning an object to this.state.
  2. Binding event handler methods to an instance.

static getDerivedStateFromProps()

getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.

This method exists for rare use cases where the state depends on changes in props over time.

This method doesn’t have access to the component instance. If you’d like, you can reuse some code between getDerivedStateFromProps() and the other class methods by extracting pure functions of the component props and state outside the class definition.

NOTE that this method is fired on every render, regardless of the cause. This is in contrast to UNSAFE_componentWillReceiveProps, which only fires when the parent causes a re-render and not as a result of a local setState.

render()

The render() method is the only required method in a class component.

When called, it should examine this.props and this.state and return one of the following types:

React elements. Typically created via JSX.

Arrays and fragments. Let you return multiple elements from render. See the documentation on fragments for more details.

String and numbers. These are rendered as text nodes in the DOM.

Booleans or null. Render nothing. (Mostly exists to support return test && <Child /> pattern, where test is boolean.)

The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it’s invoked, and it does not directly interact with the browser.

If you need to interact with the browser, perform your work in componentDidMount() or the other lifecycle methods instead. Keeping render() pure makes components easier to think about.

componentDidMount()

componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.
This method is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in componentWillUnmount().

You may call setState() immediately in componentDidMount(). It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues. In most cases, you should be able to assign the initial state in the constructor() instead. It can, however, be necessary for cases like modals and tooltips when you need to measure a DOM node before rendering something that depends on its size or position.

Updating

An update can be caused by changes to props or state. Methods are listed in the order of their execution

static getDerivedStateFromProps(): Mentioned above

shouldComponentUpdate()

Use shouldComponentUpdate() to let React know if a component’s output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior.
shouldComponentUpdate() is invoked before rendering when new props or state are being received. Defaults to true. This method is not called for the initial render or when forceUpdate() is used.

Note that returning false does not prevent child components from re-rendering when their state changes.

Currently, if shouldComponentUpdate() returns false, then UNSAFE_componentWillUpdate(), render(), and componentDidUpdate() will not be invoked. In the future React may treat shouldComponentUpdate() as a hint rather than a strict directive, and returning false may still result in a re-rendering of the component.

render()mentioned above

getSnapshotBeforeUpdate()

getSnapshotBeforeUpdate() is invoked right before the most recently rendered output is committed to e.g. the DOM. It enables your component to capture some information from the DOM (e.g. scroll position) before it is potentially changed. Any value returned by this lifecycle will be passed as a parameter to componentDidUpdate().
This use case is not common, but it may occur in UIs like a chat thread that need to handle scroll position in a special way.
A snapshot value (or null) should be returned.

componentDidUpdate()

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.
Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).

You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition or you’ll cause an infinite loop. It would also cause an extra re-rendering which, while not visible to the user, can affect the component performance. If you’re trying to “mirror” some state to a prop coming from above, consider using the prop directly instead.

NOTE componentDidUpdate() will not be invoked if shouldComponentUpdate() returns false.

Unmounting

This method is called when a component is being removed from the DOM:

componentWillUnmount()

componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount().

You should not call setState() in componentWillUnmount() because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again.

Error Handling

These methods are called when there is an error during rendering, in a lifecycle method, or in the constructor of any child component.

static getDerivedStateFromError()

This lifecycle is invoked after an error has been thrown by a descendant component. It receives the error that was thrown as a parameter and should return a value to update state.

getDerivedStateFromError() is called during the “render” phase, so side-effects are not permitted. For those use cases, use componentDidCatch() instead.

componentDidCatch()

This lifecycle is invoked after an error has been thrown by a descendant component. It receives two parameters:

  1. error - The error that was thrown.
  2. info - An object with a componentStack key containing information about which component threw the error.

componentDidCatch() is called during the “commit” phase, so side-effects are permitted. It should be used for things like logging errors:

In the event of an error, you can render a fallback UI with componentDidCatch() by calling setState, but this will be deprecated in a future release. Use static getDerivedStateFromError() to handle fallback rendering instead.

React.PureComponent is one of the most significant ways to optimize React applications that is easy and fast to implement. The usage of React.PureComponent gives a considerable increase in performance because it reduces the number of render operation in the application.

By default, a plain React.Component has shouldComponentUpdate set to always return true.
One way to deal with these extra re-renders is to change the shouldComponentUpdate function to check when your component needs to update

A common pitfall when converting from Component to PureComponent is to forget that the children need to re-render too. As with all React - if the parent doesn’t re-render the children won’t either. So if you have a PureComponent with children, those children can only update if the parent’s state or props are shallowly different (causing the parent to re-render).
You can only have a PureComponent parent if you know none of the children should re-render if the parent doesn’t re-render.
If your React component’s render function renders the same result given the same props and state, you can use React.PureComponent for a performance boost in some cases.

This is how React shallow compares (copied from React source code)

Code sample below

In the given example when we extend Display component from React.Component the render function will be called each time you click the button.

Instead if you extend the Display component from React.PureComponent the render function will be called only once. That means it calls render when the prop Is shallowly different

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import Display from "./Display";
function App() {
return (
<div className="App">
<Display chek={10} />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
import React from "react";
class Display extends React.PureComponent {
constructor(props){
super(props);
this.state = {
obj1: 1
}
}
updateMe = () => {
this.setState({
obj1: this.props.chek
});
};
render(){
console.log("render called");
return (
<>
<div>{this.state.obj1}</div>
<div>
<button type="submit" onClick={this.updateMe}>
click here
</button>
</div>
</>
)
}
}
export default Display;
import React from "react";
class Display extends React.Component {
constructor(props){
super(props);
this.state = {
obj1: 1
}
}
updateMe = () => {
this.setState({
obj1: this.props.chek
});
};
render(){
console.log("render called");
return (
<>
<div>{this.state.obj1}</div>
<div>
<button type="submit" onClick={this.updateMe}>
click here
</button>
</div>
</>
)
}
}
export default Display;

This is recommended to avoid side effects. Render method will get called immediately after the componentWillMount and no way we can make the render method wait until the API has returned.

Constructor is a place where we define the variables and not make any API calls. API calls can have side effects and should not be used inside constructor

React expects state to be available as render function will be called next after componentWillMount  and code can break if any mentioned state variable is missing which may occur in case of ajax API calls

One more reason is If we are doing server-side rendering of React components componentWillMount will get called on the server-side and again on the client, resulting in calling fetch two times. Hence, this is not definitely the place where we should integrate our APIs.

NOTE: A side effect is any application state change that is observable outside the called function other than its return value. Eg: modifying a global variable

Description

To put your best foot forward, browse through our top spring boot interview questions and answers. Just spend an hour every day before your interview on these questions. Your next spring boot interview will convert into a sure job offer.
Levels