React Interview Questions
React Interview Questions
Core React
1. What is React?
React is an open-source front-end JavaScript library that is used for building user interfaces, especially for single-page
applications. It is used for handling view layer for web and mobile apps. React was created by Jordan Walke, a software
engineer working for Facebook. React was first deployed on Facebook’s News Feed in 2011 and on Instagram in 2012.
3. What is JSX?
JSX is a XML-like syntax extension to ECMAScript (the acronym stands for JavaScript XML). Basically it just provides
syntactic sugar for the React.createElement() function, giving us expressiveness of JavaScript along with HTML like template
syntax.
In the example below text inside <h1> tag is returned as JavaScript function to the render function.jsx harmony class
Whereas a component can be declared in several different ways. It can be a class with a render() method or it can be defined
as a function. In either case, it takes props as an input, and returns a JSX tree as the
output:
5. How to create components in React?
There are two possible ways to create a component.
a. Function Components: This is the simplest way to create a component. Those are pure JavaScript functions that accept
props object as the first parameter and return React elements:
b. Class Components: You can also use ES6 class to define a component. The above function component can be written as:
This reactProp (or whatever you came up with) name then becomes a property attached to React’s native props object which
originally already exists on all components created using React library.
props.reactProp
10. What is the difference between state and props?
Both props and state are plain JavaScript objects. While both of them hold information that influences the output of render,
they are different in their functionality with respect to component. Props get passed to the component similar to function
parameters whereas state is managed within the component similar to variables declared within a function.
Instead use setState() method. It schedules an update to a component’s state object. When state changes, the component
responds by rerendering.
Note: You can directly assign to the state object either in constructor or using latest javascript’s class field declaration syntax.
13. What is the difference between HTML and React event handling?
Below are some of the main differences between HTML and React event handling,
a. In HTML, the event name usually represents in lowercase as a convention:
c. In HTML, you need to invoke the function by appending () Whereas in react you should not append () with the
function name. (refer “activateLasers” function in the first point for example)
b) Public class fields syntax: If you don’t like to use bind approach then public class fields syntax can be used to correctly
bind callbacks.
c) Arrow functions in callbacks: You can use arrow functions directly in the callbacks.
Note: If the callback is passed a prop to child components, those components might do an extra re-rendering. In those cases,
it is preferred to go with. bind() or public class fields syntax approach considering performance.
18. What is “key” prop and what is the benefit of using it in arrays of elements?
A key is a special string attribute you should include when creating arrays of elements. Key prop helps React identify which
items have changed, are added, or are removed.
Most often we use ID from our data as key:
When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort:
Note:
a. Using indexes for keys is not recommended if the order of items may change. This can negatively impact
performance and may cause issues with component state.
b. If you extract list item as separate component, then apply keys on list component instead of li tag.
c. There will be a warning message in the console if the key prop is not present on list items.
You can also use ref callbacks approach regardless of React version. For example, the search bar component’s input element is
accessed as follows, jsx harmony class SearchBar extends Component
{ constructor(props) { super(props);
this.txtSearch = null; this.state = { term: ''}; this.setInputSearchRef = e => { this.txtSearch = e; } }
onInputChange(event) { this.setState({ term: this.txtSearch.value }); } render() { return ( <input
value={this.state.onChange={this.onInputChange.bind(this)} ref={this.setInputSearchRef}/> ); } }
You can also use refs in function components using closures. Note: You can also use inline ref callbacks even though it is not
a recommended approach.
21. What are forward refs?
Ref forwarding is a feature that lets some components take a ref they receive, and pass it further down to a child.
“‘jsx harmony const ButtonElement = React.forwardRef((props, ref) => ( {props.children} ));
// Create ref to the DOM button: const ref = React.createRef(); {‘Forward Ref’} “‘
22. Which is preferred option with in callback refs and find-DOMNode()?
It is preferred to use callback refs over findDOMNode() API. Because findDOMNode() prevents certain improvements in React in
the future.
The legacy approach of using findDOMNode:
The recommended approach is:
26. What is the difference between Shadow DOM and Virtual DOM?
The Shadow DOM is a browser technology designed primarily for scoping variables and CSS in web components. The Virtual
DOM is a concept implemented by libraries in JavaScript on top of browser APIs.
27. What is React Fiber?
Fiber is the new reconciliation engine or reimplementation of core algorithm in React v16. The goal of React Fiber is to increase its
suitability for areas like animation, layout, gestures, ability to pause, abort, or reuse work and assign priority to different types of
updates; and new concurrency primitives.
React 16.3+
getDerivedStateFromProps: Invoked right before calling render() and is invoked on every render. This exists for
rare use cases where you need a derived state. Worth reading if you need derived state.
componentDidMount: Executed after first rendering and where all AJAX requests, DOM or state updates, and set
up event listeners should occur.
shouldComponentUpdate: Determines if the component will be updated or not. By default, it returns true. If you are
sure that the component doesn’t need to render after the state or props are updated, you can return a false value. It is
a great place to improve
performance as it allows you to prevent a re-render if component receives a new prop.
getSnapshotBeforeUpdate: Executed right before rendered output is committed to the DOM. Any value returned by
this will be passed into componentDidUpdate(). This is useful to capture information from the DOM i.e. scroll position.
componentDidUpdate: Mostly it is used to update the DOM in response to prop or state changes. This will not fire if
shouldComponentUpdate() returns false.
componentWillUnmount It will be used to cancel any outgoing network requests, or remove all event listeners
associated with the component.
Multi-line comments:
40. What is the purpose of using super constructor with props argument?
A child class constructor cannot make use of this reference until the super() method has been called. The same applies to ES6
sub-classes as well. The main reason for passing props parameter to super() call is to access this.props in your child
constructors.
Passing props:
43. What would be the common mistake of function being called every time the component renders?
You need to make sure that function is not being called while passing the function as a parameter.
jsx harmony render() { // Wrong: handleClick is called instead of passed as a reference! return <button
onClick={this.handleClick()}>{'Click Me'}</button> }
Instead, pass the function itself without parenthesis:
jsx harmony render() { // Correct: handleClick is passed as a reference! return <button
onClick={this.handleClick}>{'Click
Me'}</button> }
There is also a shorter syntax, but it’s not supported in many tools:
The first argument is any render-able React child, such as an element, string, or fragment. The second argument is a DOM
element.
User.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired
}
56. What are the recommended ways for static type checking?
Normally we use PropTypes library (React.PropTypes moved to a prop-types package since React v15.5) for type checking in
the React applications. For large code bases, it is recommended to use static type checkers such as Flow or TypeScript, that
perform type checking at compile time and provide auto-completion features.
If you use element data for unique key, assuming todo.id is unique to this list and stable, React would be able to reorder
elements without needing to reevaluate them as much.
Note: Decorators are a feature that didn’t make it into ES7, but are currently a stage 2 proposal.
75. What are the lifecycle methods going to be deprecated in React v16?
The following lifecycle methods going to be unsafe coding practices and will be more problematic with async rendering.
a. componentWillMount()
b. componentWillReceiveProps()
c. componentWillUpdate()
Starting with React v16.3 these methods are aliased with UNSAFE_ prefix, and the unprefixed version will be removed in
React v17.
This lifecycle method along with componentDidUpdate() covers all the use cases of componentWillReceiveProps().
The preferred approach is to call setState() with function rather than object. That function will receive the previous state as the
first argument, and the props at the time the update is applied as the second argument.
In the example above, the strict mode checks apply to <ComponentOne> and <ComponentTwo> components only.
Checking isMounted() before calling setState() does eliminate the warning, but it also defeats the purpose of the warning.
Using isMounted() is a code smell because the only reason you would check is because you think you might be holding a
reference after the component has unmounted.
An optimal solution would be to find places where setState() might be called after a component has unmounted, and fix them.
Such situations most commonly occur due to callbacks, when a component is waiting for some data and gets unmounted
before the data arrives. Ideally, any callbacks should be canceled in componentWillUnmount(), prior to unmounting.
This is useful for supplying browser-specific non-standard attributes, trying new DOM APIs, and integrating with opinionated
third-party libraries.
Note: React.createClass() is deprecated and removed in React v16. Use plain JavaScript classes instead.
90. Can you force a component to re-render without calling set-State?
By default, when your component’s state or props change, your component will re-render. If your render() method depends on
some other data, you can tell React that the component needs re-rendering by calling forceUpdate().
It is recommended to avoid all uses of forceUpdate() and only read from this.props and this.state in render().
91. What is the difference between super() and super(props) in React using ES6 classes?
When you want to access this.props in constructor() then you should pass props to super() method.
Outside constructor() both will display same value for this.props.
125.How to make AJAX call and in which component lifecycle methods should I make an AJAX call?
You can use AJAX libraries such as Axios, jQuery AJAX, and the browser built-in fetch. You should fetch data in the
componentDidMount() lifecycle method. This is so you can use setState() to update your component when the data is
retrieved.
For example, the employees list fetched from API and set local state:
“‘jsx harmony class MyComponent extends React.Component { constructor( props) { super(props) this.state = { employees:
[], error: null } }
componentDidMount() { fetch(‘https://api.example.com/items’) .then(res => res.json()) .then( (result) =>
{ this.setState({ employees: result.employees }) }, (error) => { this.setState({ error }) } )
}
render() { const { error, employees } = this.state if (error) { return
Error: {error.message} ; } else { return (
{employees.map(employee => (
{employee.name}-{employee.experience} ))} ) } } } “‘
133.Why you get “Router may have only one child element” warning?
You have to wrap your Route’s in a <Switch> block because <Switch> is unique in that it renders a route exclusively.
At first you need to add Switch to your imports:
b. You should use the <Router> component instead of built-in routers. Import the above history.js inside index.js file:
“‘jsx harmony import { Router } from ‘react-router-dom’ import history from ‘./history’ import App from ‘./App’
ReactDOM.render(( ), holder) “‘
c. You can also use push method of history object similar to built-in history object:
147.What is Jest?
Jest is a JavaScript unit testing framework created by Facebook based on Jasmine and provides automated mock creation
and a jsdom environment. It’s often used for testing components.
Finally, run yarn test or npm test and Jest will print a result:
R
React Redux
150.What is flux?
Flux is an application design paradigm used as a replacement for the more traditional MVC pattern. It is not a framework or a
library but a new kind of architecture that complements React and the concept of Unidirectional Data Flow. Facebook uses this
pattern internally when working with React.
The workflow between dispatcher, stores and views components with distinct inputs and outputs as follows:
Figure 7: flux
151.What is Redux?
Redux is a predictable state container for JavaScript apps based on the Flux design pattern. Redux can be used together with
React, or with any other view library. It is tiny (about 2kB) and has no dependencies.
mapDispatchToProps() is a utility which will help your component to fire an action event (dispatching action which may cause
change of application state):
It is recommended to always use the “object shorthand” form for the mapDispatchToProps.
Redux wraps it in another function that looks like (…args) => dispatch( onTodoClick(…args)), and pass that wrapper function
as a prop to your component.
In case of using redux-persist, you may also need to clean your storage. redux-persist keeps a copy of your state in a storage
engine. First, you need to import the appropriate storage engine and then, to parse the state before setting it to undefined and
clean each storage state key.
162.Whats the purpose of at symbol in the Redux connect decorator?
The **@** symbol is in fact a JavaScript expression used to signify decorators. Decorators make it possible to annotate and
modify classes and properties at design time.
Let’s take an example setting up Redux without and with a decorator.
Without decorator:
With decorator:
The above examples are almost similar except the usage of decorator. The decorator syntax isn’t built into any JavaScript
runtimes yet, and is still experimental and subject to change. You can use babel for the decorators support.
Due to it having quite a few performance optimizations and generally being less likely to cause bugs, the Redux developers
almost always recommend using connect() over accessing the store directly (using context API).
173.What is redux-saga?
redux-saga is a library that aims to make side effects (asynchronous things like data fetching and impure things like accessing
the browser cache) in React/Redux applications easier and better.
It is available in NPM:
$ npm install --save redux-saga
192.What is Flow?
Flow is a static type checker designed to find type errors in JavaScript.
Flow types can express much more fine-grained distinctions than traditional type systems. For example, Flow helps you catch
errors involving null, unlike most type systems.
These two variables, Title and Wrapper, are now components that you can render just like any other react component.
200.What is Relay?
Relay is a JavaScript framework for providing a data layer and client-server communication to web applications using the
React view layer.