ReactJS Interview Questions & Answers
ReactJS Interview Questions & Answers
List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are coming
soon!!
Starred Watch
master
sudheerj Merge pull request #227 from aduyng/master … last week 398
View code
README.md
Explore the Best Free Resource to learn React and kickstart your journey as a react
developer. Earn a free certification in just 40 days.
Note: This repository is specific to ReactJS. Please check Javascript Interview questions
for core javascript questions.
Table of Contents
No. Questions
Core React
1 What is React?
3 What is JSX?
18 What is "key" prop and what is the benefit of using it in arrays of elements?
37 What is context?
41 What is reconciliation?
What would be the common mistake of function being called every time the
43
component renders?
59 What is ReactDOMServer?
What is the difference between super() and super(props) in React using ES6
91
classes?
110 How can we find the version of React at runtime in the browser?
117 How to import and export components using react and ES6?
How to make AJAX call and In which component lifecycle methods should I
127
make an AJAX call?
React Router
135 Why you get "Router may have only one child element" warning?
React Internationalization
React Testing
React Redux
165 What is the difference between React context and React Redux?
170 What is the difference between component and container in React Redux?
177 What are the differences between call and put in redux-saga
React Native
Miscellaneous
209 Does the statics object work with ES6 classes in React?
No. Questions
213 How React PropTypes allow different type for one prop?
Do I need to keep all my state into Redux? Should I ever use react internal
219
state?
224 How do you render Array, Strings and Numbers in React 16 Version?
233 Why do you not need error boundaries for event handlers?
No. Questions
234 What is the difference between try catch block and error boundaries?
237 What is the benefit of component stack trace from error boundary?
267 What are the conditions to safely use the index as a key?
270 What are the advantages of formik over redux form library?
281 How do you solve performance corner cases while using context?
Why do you need additional care for component libraries while using forward
284
refs?
291 What are the problems of using render props with pure components?
298 What is the difference between Real DOM and Virtual DOM?
Can you list down top websites or applications using react as front end
300
framework?
320 What is the difference between async mode and concurrent mode?
How do you make sure that user remains authenticated on page refresh while
325
using Context API State Management?
327 How is the new JSX transform different from old transform?
334 What are the differences between useEffect and useLayoutEffect hooks
335 What are the differences between Functional and Class Components
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.
Back to Top
Uses JSX syntax, a syntax extension of JS that allows developers to write HTML
in their JS code.
It uses VirtualDOM instead of RealDOM considering that RealDOM
manipulations are expensive.
Supports server-side rendering.
Follows Unidirectional data flow or data binding.
Uses reusable/composable UI components to develop the view.
Back to Top
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.
See Class
Back to Top
{
type: 'div',
props: {
children: 'Login',
id: 'login-btn'
}
}
Back to Top
ii. Class Components: You can also use ES6 class to define a component. The
above function component can be written as:
Back to Top
However, from React 16.8 with the addition of Hooks, you could use state , lifecycle
methods and other features that were only available in class component right in your
function component. So, it is always recommended to use Function components,
unless you need a React functionality whose Function component equivalent is not
present yet, like Error Boundaries.
Back to Top
Back to Top
return (
<div>
<h1>{message}</h1>
</div>
);
}
See Class
State is similar to props, but it is private and fully controlled by the component ,i.e., it
is not accessible to any other component till the owner component decides to pass it.
Back to Top
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
Back to Top
Back to Top
//Wrong
this.state.message = "Hello world";
//Correct
this.setState({ message: "Hello World" });
Note: You can directly assign to the state object either in constructor or using latest
javascript's class field declaration syntax.
Back to Top
12. What
is the purpose of callback function as an argument of
setState() ?
The callback function is invoked when setState finished and the component gets
rendered. Since setState() is asynchronous the callback function is used for any
post action.
Note: It is recommended to use lifecycle method rather than this callback function.
Back to Top
13. What
is the difference between HTML and React event
handling?
Below are some of the main differences between HTML and React event handling,
<button onclick="activateLasers()"></button>
<button onClick={activateLasers}>
<a
href="#"
onclick='console.log("The link was clicked."); return false;'
/>
iii. 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)
Back to Top
ii. 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.
handleClick = () => {
console.log("this is:", this);
};
handleClick() {
console.log('Click happened');
}
render() {
return <button onClick={() => this.handleClick()}>Click Me</butto
}
Note: If the callback is passed as 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.
Back to Top
Apart from these two approaches, you can also pass arguments to a function which is
defined as arrow function
Back to Top
Back to Top
<h1>Hello!</h1>;
{
messages.length > 0 && !isLogin ? (
<h2>You have {messages.length} unread messages.</h2>
) : (
<h2>You don't have unread messages.</h2>
);
}
Back to Top
18. Whatis "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.
Keys should be unique among its siblings. 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:
i. 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.
ii. If you extract list item as separate component then apply keys on list component
instead of li tag.
iii. There will be a warning message in the console if the key prop is not present
on list items.
Back to Top
Back to Top
ii. You can also use ref callbacks approach regardless of React version. For
example, the search bar component's input element is accessed as follows,
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.term}
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.
Back to Top
Back to Top
22. Which
is preferred option with in callback refs and
findDOMNode()?
It is preferred to use callback refs over findDOMNode() API. Because
findDOMNode() prevents certain improvements in React in the future.
render() {
return <div />;
}
}
render() {
return <div ref={this.node} />;
}
}
Back to Top
ii. They are not composable — if a library puts a ref on the passed child, the user
can't put another ref on it. Callback refs are perfectly composable.
iii. They don't work with static analysis like Flow. Flow can't guess the magic that
framework does to make the string ref appear on this.refs , as well as its type
(which could be different). Callback refs are friendlier to static analysis.
iv. It doesn't work as most people would expect with the "render callback" pattern
(e.g. )
render() {
return (
<DataTable data={this.props.data} renderRow={this.renderRow} />
);
}
}
Back to Top
Back to Top
ii. Then the difference between the previous DOM representation and the new one
is calculated.
iii. Once the calculations are done, the real DOM will be updated with only the things
that have actually changed.
Back to Top
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.
Back to Top
Back to Top
from documentation
Back to Top
For example, to write all the names in uppercase letters, we use handleChange as
below,
handleChange(event) {
this.setState({value: event.target.value.toUpperCase()})
}
Back to Top
In the below UserProfile component, the name input is accessed using ref.
handleSubmit(event) {
alert("A name was submitted: " + this.input.current.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
{"Name:"}
<input type="text" ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
Back to Top
31. What
is the difference between createElement and
cloneElement?
JSX elements will be transpiled to React.createElement() functions to create
React elements which are going to be used for the object representation of UI.
Whereas cloneElement is used to clone an element and pass it new props.
Back to Top
Back to Top
ii. Updating: In this phase, the component gets updated in two ways, sending the
new props and updating the state either from setState() or forceUpdate() .
This phase covers getDerivedStateFromProps() , shouldComponentUpdate() ,
render() , getSnapshotBeforeUpdate() and componentDidUpdate() lifecycle
methods.
iii. Unmounting: In this last phase, the component is not needed and gets
unmounted from the browser DOM. This phase includes
componentWillUnmount() lifecycle method.
It's worth mentioning that React internally has a concept of phases when applying
changes to the DOM. They are separated as follows
i. Render The component will render without any side effects. This applies to Pure
components and in this phase, React can pause, abort, or restart the render.
ii. Pre-commit Before the component actually applies the changes to the DOM,
there is a moment that allows React to read from the DOM through the
getSnapshotBeforeUpdate() .
iii. Commit React works with the DOM and executes the final lifecycles respectively
componentDidMount() for mounting, componentDidUpdate() for updating, and
componentWillUnmount() for unmounting.
Back to Top
React 16.3+
Back to Top
We call them pure components because they can accept any dynamically provided
child component but they won't modify or copy any behavior from their input
components.
Back to Top
function HOC(WrappedComponent) {
return class Test extends Component {
render() {
const newProps = {
title: "New Header",
footer: false,
showFeatureX: false,
showFeatureY: true,
};
Back to Top
Back to Top
There are several methods available in the React API to work with this prop. These
include React.Children.map , React.Children.forEach , React.Children.count ,
React.Children.only , React.Children.toArray .
ReactDOM.render(
<MyDiv>
<span>{"Hello"}</span>
<span>{"World"}</span>
</MyDiv>,
node
);
Back to Top
<div>
{/* Single-line comments(In vanilla JavaScript, the single-line comment
{`Welcome ${user}, let's play React`}
</div>
Multi-line comments:
<div>
{/* Multi-line comments for more than
one line */}
{`Welcome ${user}, let's play React`}
</div>
Back to Top
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:
render() {
// no difference outside constructor
console.log(this.props); // prints { name: 'John', age: 42 }
}
}
The above code snippets reveals that this.props is different only within the
constructor. It would be the same outside the constructor.
Back to Top
Back to Top
handleInputChange(event) {
this.setState({ [event.target.id]: event.target.value })
}
Back to Top
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.
render() {
// Wrong: handleClick is called instead of passed as a reference!
return <button onClick={this.handleClick()}>{'Click Me'}</button>
}
render() {
// Correct: handleClick is passed as a reference!
return <button onClick={this.handleClick}>{'Click Me'}</button>
}
Back to Top
// MoreComponents.js
export const SomeComponent = /* ... */;
export const UnusedComponent = /* ... */;
// IntermediateComponent.js
export { SomeComponent as default } from "./MoreComponents.js";
Now you can import the module using lazy function as below,
Back to Top
45. Why React uses className over class attribute?
class is a keyword in JavaScript, and JSX is an extension of JavaScript. That's the
principal reason why React uses className instead of class . Pass a string as the
className prop.
render() {
return <span className={'menu navigation-menu'}>{'Menu'}</span>
}
Back to Top
render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
)
}
There is also a shorter syntax, but it's not supported in many tools:
render() {
return (
<>
<ChildA />
<ChildB />
<ChildC />
</>
)
}
Back to Top
47. Why fragments are better than container divs?
Below are the list of reasons,
i. Fragments are a bit faster and use less memory by not creating an extra DOM
node. This only has a real benefit on very large and deep trees.
ii. Some CSS mechanisms like Flexbox and CSS Grid have a special parent-child
relationships, and adding divs in the middle makes it hard to keep the desired
layout.
iii. The DOM Inspector is less cluttered.
Back to Top
ReactDOM.createPortal(child, container);
The first argument is any render-able React child, such as an element, string, or
fragment. The second argument is a DOM element.
Back to Top
Back to Top
render() {
// ...
}
}
Hooks let you use state and other React features without writing classes.
return (
// JSX
)
}
Back to Top
i. PropTypes.number
ii. PropTypes.string
iii. PropTypes.array
iv. PropTypes.object
v. PropTypes.func
vi. PropTypes.node
vii. PropTypes.element
viii. PropTypes.bool
ix. PropTypes.symbol
x. PropTypes.any
render() {
return (
<>
<h1>{`Welcome, ${this.props.name}`}</h1>
<h2>{`Age, ${this.props.age}`}</h2>
</>
);
}
}
Back to Top
Back to Top
Back to Top
componentDidCatch(error, info) {
// You can also log the error to an error reporting service
logErrorToMyService(error, info);
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>{"Something went wrong."}</h1>;
}
return this.props.children;
}
}
<ErrorBoundary>
<MyWidget />
</ErrorBoundary>
Back to Top
Back to Top
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.
Back to Top
The react-dom package provides DOM-specific methods that can be used at the
top level of your app. Most of the components are not required to use this module.
Some of the methods of this package are:
i. render()
ii. hydrate()
iii. unmountComponentAtNode()
iv. findDOMNode()
v. createPortal()
Back to Top
This method is used to render a React element into the DOM in the supplied container
and return a reference to the component. If the React element was previously
rendered into container, it will perform an update on it and only mutate the DOM as
necessary to reflect the latest changes.
If the optional callback is provided, it will be executed after the component is rendered
or updated.
Back to Top
i. renderToString()
ii. renderToStaticMarkup()
For example, you generally run a Node-based web server like Express, Hapi, or Koa,
and you call renderToString to render your root component to a string, which you
then send as response.
// using Express
import { renderToString } from "react-dom/server";
import MyPage from "./MyPage";
Back to Top
function createMarkup() {
return { __html: "First · Second" };
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}
Back to Top
const divStyle = {
color: "blue",
backgroundImage: "url(" + imgUrl + ")",
};
function HelloWorldComponent() {
return <div style={divStyle}>Hello World!</div>;
}
Style keys are camelCased in order to be consistent with accessing the properties on
DOM nodes in JavaScript (e.g. node.style.backgroundImage ).
Back to Top
i. React event handlers are named using camelCase, rather than lowercase.
ii. With JSX you pass a function as the event handler, rather than a string.
Back to Top
When you use setState() , then apart from assigning to the object state React also
re-renders the component and all its children. You would get error like this: Can only
update a mounted or mounting component. So we need to use this.state to
initialize variables inside constructor.
Back to Top
64. What is the impact of indexes as keys?
Keys should be stable, predictable, and unique so that React can keep track of
elements.
In the below code snippet each element's key will be based on ordering, rather than
tied to the data that is being represented. This limits the optimizations that React can
do.
{
todos.map((todo, index) => <Todo {...todo} key={index} />);
}
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.
{
todos.map((todo) => <Todo {...todo} key={todo.id} />);
}
Back to Top
65. Is
it good to use setState() in componentWillMount()
method?
Yes, it is safe to use setState() inside componentWillMount() method. But at the
same it is recommended to avoid async initialization in componentWillMount()
lifecycle method. componentWillMount() is invoked immediately before mounting
occurs. It is called before render() , therefore setting state in this method will not
trigger a re-render. Avoid introducing any side-effects or subscriptions in this method.
We need to make sure async calls for component initialization happened in
componentDidMount() instead of componentWillMount() .
componentDidMount() {
axios.get(`api/todos`)
.then((result) => {
this.setState({
messages: [...result.data]
})
})
}
Back to Top
this.state = {
records: [],
inputValue: this.props.inputValue,
};
}
render() {
return <div>{this.state.inputValue}</div>;
}
}
this.state = {
record: [],
};
}
render() {
return <div>{this.props.inputValue}</div>;
}
}
Back to Top
Back to Top
68. Why
we need to be careful when spreading props on DOM
elements?
When we spread props we run into the risk of adding unknown HTML attributes, which
is a bad practice. Instead we can use prop destructuring with ...rest operator, so it
will add only required props.
For example,
@setTitle("Profile")
class Profile extends React.Component {
//....
}
/*
title is a string that will be set as a document title
WrappedComponent is what our decorator will receive when
put directly above a component class as seen in the example above
*/
const setTitle = (title) => (WrappedComponent) => {
return class extends React.Component {
componentDidMount() {
document.title = title;
}
render() {
return <WrappedComponent {...this.props} />;
}
};
};
Note: Decorators are a feature that didn't make it into ES7, but are currently a stage 2
proposal.
Back to Top
For example moize library can memoize the component in another component.
Back to Top
ReactDOMServer.renderToString(<App />);
This method will output the regular HTML as a string, which can be then placed inside
a page body as part of the server response. On the client side, React detects the pre-
rendered content and seamlessly picks up where it left off.
Back to Top
Back to Top
# Installation
$ npm install -g create-react-app
Back to Top
Back to Top
i. componentWillMount()
ii. componentWillReceiveProps()
iii. componentWillUpdate()
Starting with React v16.3 these methods are aliased with UNSAFE_ prefix, and the
unprefixed version will be removed in React v17.
Back to Top
This lifecycle method along with componentDidUpdate() covers all the use cases of
componentWillReceiveProps() .
Back to Top
77. What is the purpose of getSnapshotBeforeUpdate()
lifecycle method?
The new getSnapshotBeforeUpdate() lifecycle method is called right before DOM
updates. The return value from this method will be passed as the third parameter to
componentDidUpdate() .
This lifecycle method along with componentDidUpdate() covers all the use cases of
componentWillUpdate() .
Back to Top
Back to Top
also
Back to Top
80. What
is the recommended ordering of methods in component
class?
Recommended ordering of methods from mounting to render stage:
i. static methods
ii. constructor()
iii. getChildContext()
iv. componentWillMount()
v. componentDidMount()
vi. componentWillReceiveProps()
vii. shouldComponentUpdate()
viii. componentWillUpdate()
ix. componentDidUpdate()
x. componentWillUnmount()
xi. click handlers or event handlers like onClickSubmit() or
onChangeDescription()
Back to Top
const PAGES = {
home: HomePage,
about: AboutPage,
services: ServicesPage,
contact: ContactPage,
};
// The keys of the PAGES object can be used in the prop types to catch de
Page.propTypes = {
page: PropTypes.oneOf(Object.keys(PAGES)).isRequired,
};
Back to Top
Let's say the initial count value is zero. After three consecutive increment operations,
the value is going to be incremented only by one.
(OR)
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
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.
// Correct
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment,
}));
Back to Top
function ExampleApplication() {
return (
<div>
<Header />
<React.StrictMode>
<div>
<ComponentOne />
<ComponentTwo />
</div>
</React.StrictMode>
<Header />
</div>
);
}
In the example above, the strict mode checks apply to <ComponentOne> and
<ComponentTwo> components only.
Back to Top
One of the most commonly used mixins is PureRenderMixin . You might be using it
in some components to prevent unnecessary re-renders when the props and state are
shallowly equal to the previous props and state:
if (this.isMounted()) {
this.setState({...})
}
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.
Back to Top
i. onPointerDown
ii. onPointerMove
iii. onPointerUp
iv. onPointerCancel
v. onGotPointerCapture
vi. onLostPointerCapture
vii. onPointerEnter
viii. onPointerLeave
ix. onPointerOver
x. onPointerOut
Back to Top
You can define component class which name starts with lowercase letter, but when it's
imported it should have capital letter. Here lowercase is fine:
While when imported in another file it should start with capital letter:
The component names should start with an uppercase letter but there are few
exceptions to this convention. The lowercase tag names with a dot (property
accessors) are still considered as valid component names. For example, the below
tag can be compiled to a valid component,
render() {
return (
<obj.component/> // `React.createElement(obj.component)`
)
}
Back to Top
<div />
This is useful for supplying browser-specific non-standard attributes, trying new DOM
APIs, and integrating with opinionated third-party libraries.
Back to Top
Using React.createClass() :
Back to Top
90. Can
you force a component to re-render without calling
setState?
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() .
component.forceUpdate(callback);
Back to Top
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.
Using super(props) :
class MyComponent extends React.Component {
constructor(props) {
super(props);
console.log(this.props); // { name: 'John', ... }
}
}
Using super() :
Back to Top
For example, the items array of objects is mapped into an array of components:
<tbody>
{items.map((item) => (
<SomeComponent key={item.id} name={item.name} />
))}
</tbody>
<tbody>
for (let i = 0; i < items.length; i++) {
<SomeComponent key={items[i].id} name={items[i].name} />
}
</tbody>
This is because JSX tags are transpiled into function calls, and you can't use
statements inside expressions. This may change thanks to do expressions which
are stage 1 proposal.
Back to Top
But you can put any JS expression inside curly braces as the entire attribute value. So
the below expression works:
Back to Top
ReactComponent.propTypes = {
arrayWithShape: React.PropTypes.arrayOf(
React.PropTypes.shape({
color: React.PropTypes.string.isRequired,
fontSize: React.PropTypes.number.isRequired,
})
).isRequired,
};
Back to Top
95. How to conditionally apply class attributes?
You shouldn't use curly braces inside quotes because it is going to be evaluated as a
string.
Instead you need to move curly braces outside (don't forget to include spaces
between class names):
Back to Top
Back to Top
Back to Top
<label for={'user'}>{'User'}</label>
<input type={'text'} id={'user'} />
<label htmlFor={'user'}>{'User'}</label>
<input type={'text'} id={'user'} />
Back to Top
If you're using React Native then you can use the array notation:
Back to Top
componentWillMount() {
this.updateDimensions();
}
componentDidMount() {
window.addEventListener("resize", this.updateDimensions);
}
componentWillUnmount() {
window.removeEventListener("resize", this.updateDimensions);
}
updateDimensions() {
this.setState({
width: window.innerWidth,
height: window.innerHeight,
});
}
render() {
return (
<span>
{this.state.width} x {this.state.height}
</span>
);
}
}
Back to Top
101. What
is the difference between setState() and
replaceState() methods?
When you use setState() the current and previous states are merged.
replaceState() throws out the current state, and replaces it with only what you
provide. Usually setState() is used unless you really need to remove all previous
keys for some reason. You can also set state to false / null in setState()
instead of using replaceState() .
Back to Top
Back to Top
For example, let's create a removeItem() method for updating the state.
removeItem(index) {
this.setState({
data: this.state.data.filter((item, i) => i !== index)
})
}
Back to Top
render() {
return true
}
render() {
return null
}
render() {
return []
}
render() {
return ""
}
render() {
return <React.Fragment></React.Fragment>
}
render() {
return <></>
}
render() {
return undefined
}
Back to Top
Back to Top
Back to Top
render() {
return (
<div>
<input defaultValue={"Won't focus"} />
<input
ref={(input) => (this.nameInput = input)}
defaultValue={"Will focus"}
/>
</div>
);
}
}
useEffect(() => {
inputElRef.current.focus();
}, []);
return (
<div>
<input defaultValue={"Won't focus"} />
<input ref={inputElRef} defaultValue={"Will focus"} />
</div>
);
};
Back to Top
this.setState((prevState) => ({
user: {
...prevState.user,
age: 42,
},
}));
Back to Top
110. How
can we find the version of React at runtime in the
browser?
You can use React.version to get the version.
ReactDOM.render(
<div>{`React version: ${REACT_VERSION}`}</div>,
document.getElementById("app")
);
Back to Top
111. What
are the approaches to include polyfills in your create-
react-app ?
There are approaches to include polyfills in create-react-app,
Create a file called (something like) polyfills.js and import it into root
index.js file. Run npm install core-js or yarn add core-js and import
your specific required features.
import "core-js/fn/array/find";
import "core-js/fn/array/includes";
import "core-js/fn/number/is-nan";
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=defa
Back to Top
"scripts": {
"start": "set HTTPS=true && react-scripts start"
}
Back to Top
NODE_PATH=src/app
After that restart the development server. Now you should be able to import anything
inside src/app without relative paths.
Back to Top
history.listen(function (location) {
window.ga("set", "page", location.pathname + location.search);
window.ga("send", "pageview", location.pathname + location.search);
});
Back to Top
componentDidMount() {
this.interval = setInterval(() => this.setState({ time: Date.now() }),
}
componentWillUnmount() {
clearInterval(this.interval)
}
Back to Top
<div
style={{
transform: "rotate(90deg)",
WebkitTransform: "rotate(90deg)", // note the capital 'W' here
msTransform: "rotate(90deg)", // 'ms' is the only lowercase vendor pr
}}
/>
Back to Top
117. How to import and export components using React and ES6?
You should use default for exporting the components
With the export specifier, the MyProfile is going to be the member and exported to this
module and the same can be imported without mentioning the name in other
components.
Back to Top
Back to Top
Back to Top
this.inputElement.click();
Back to Top
Back to Top
One common way to structure projects is locate CSS, JS, and tests together,
grouped by feature or route.
common/
├─ Avatar.js
├─ Avatar.css
├─ APIUtils.js
└─ APIUtils.test.js
feed/
├─ index.js
├─ Feed.js
├─ Feed.css
├─ FeedStory.js
├─ FeedStory.test.js
└─ FeedAPI.js
profile/
├─ index.js
├─ Profile.js
├─ ProfileHeader.js
├─ ProfileHeader.css
└─ ProfileAPI.js
ii. Grouping by file type:
api/
├─ APIUtils.js
├─ APIUtils.test.js
├─ ProfileAPI.js
└─ UserAPI.js
components/
├─ Avatar.js
├─ Avatar.css
├─ Feed.js
├─ Feed.css
├─ FeedStory.js
├─ FeedStory.test.js
├─ Profile.js
├─ ProfileHeader.js
└─ ProfileHeader.css
Back to Top
Back to Top
Back to Top
Back to Top
127. 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:
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 <div>Error: {error.message}</div>;
} else {
return (
<ul>
{employees.map((employee) => (
<li key={employee.name}>
{employee.name}-{employee.experience}
</li>
))}
</ul>
);
}
}
}
Back to Top
Libraries such as React Router and DownShift are using this pattern.
React Router
Back to Top
Back to Top
Back to Top
i. <BrowserRouter>
ii. <HashRouter>
iii. <MemoryRouter>
The above components will create browser, hash, and memory history instances.
React Router v4 makes the properties and methods of the history instance
associated with your router available through the context in the router object.
Back to Top
132. What
is the purpose of push() and replace() methods of
history ?
A history instance has two methods for navigation purpose.
i. push()
ii. replace()
If you think of the history as an array of visited locations, push() will add a new
location to the array and replace() will replace the current location in the array with
the new one.
Back to Top
The withRouter() higher-order function will inject the history object as a prop
of the component. This object provides push() and replace() methods to
avoid the usage of context.
The <Route> component passes the same props as withRouter() , so you will
be able to access the history methods through the history prop.
Button.contextTypes = {
history: React.PropTypes.shape({
push: React.PropTypes.func.isRequired,
}),
};
Back to Top
Back to Top
135. 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.
<Router>
<Switch>
<Route {/* ... */} />
<Route {/* ... */} />
</Switch>
</Router>
Back to Top
136. How
to pass params to history.push method in React
Router v4?
While navigating you can pass props to the history object:
this.props.history.push({
pathname: "/template",
search: "?name=sudheer",
state: { detail: response.data },
});
<Switch>
<Route exact path="/" component={Home} />
<Route path="/user" component={User} />
<Route component={NotFound} />
</Switch>
Back to Top
i. Create a module that exports a history object and import this module across
the project.
ii. You should use the <Router> component instead of built-in routers. Import the
above history.js inside index.js file:
ReactDOM.render(
<Router history={history}>
<App />
</Router>,
holder
);
iii. You can also use push method of history object similar to built-in history
object:
// some-other-file.js
import history from "./history";
history.push("/go-here");
Back to Top
React Internationalization
Back to Top
Back to Top
141. What are the main features of React Intl?
Below are the main features of React Intl,
Back to Top
<FormattedMessage
id={"account"}
defaultMessage={"The amount is less than minimum balance."}
/>
formatMessage(messages.accountMessage);
Back to Top
MyComponent.propTypes = {
intl: intlShape.isRequired,
};
Back to Top
MyComponent.propTypes = {
intl: intlShape.isRequired,
};
Back to Top
MyComponent.propTypes = {
intl: intlShape.isRequired,
};
React Testing
Back to Top
function MyComponent() {
return (
<div>
<span className={"heading"}>{"Title"}</span>
<span className={"description"}>{"Description"}</span>
</div>
);
}
// in your test
const renderer = new ShallowRenderer();
renderer.render(<MyComponent />);
expect(result.type).toBe("div");
expect(result.props.children).toEqual([
<span className={"heading"}>{"Title"}</span>,
<span className={"description"}>{"Description"}</span>,
]);
Back to Top
This package provides a renderer that can be used to render components to pure
JavaScript objects, without depending on the DOM or a native mobile environment.
This package makes it easy to grab a snapshot of the platform view hierarchy (similar
to a DOM tree) rendered by a ReactDOM or React Native without using a browser or
jsdom .
console.log(testRenderer.toJSON());
// {
// type: 'a',
// props: { href: 'https://www.facebook.com/' },
// children: [ 'Facebook' ]
// }
Back to Top
Back to Top
Back to Top
Back to Top
{
"scripts": {
"test": "jest"
}
}
Finally, run yarn test or npm test and Jest will print a result:
$ yarn test
PASS ./sum.test.js
✓ adds 1 + 2 to equal 3 (2ms)
React Redux
Back to Top
The workflow between dispatcher, stores and views components with distinct inputs
and outputs as follows:
Back to Top
Back to Top
i. Single source of truth: The state of your whole application is stored in an object
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.
ii. State is read-only: The only way to change the state is to emit an action, an
object describing what happened. This ensures that neither the views nor the
network callbacks will ever write directly to the state.
iii. Changes are made with pure functions: To specify how the state tree is
transformed by actions, you write reducers. Reducers are just pure functions that
take the previous state and an action as parameters, and return the next state.
Back to Top
156. What
is the difference between mapStateToProps() and
mapDispatchToProps() ?
mapStateToProps() is a utility which helps your component get updated state
(which is updated by some other components):
Redux wraps it in another function that looks like (…args) => dispatch(onTodoClick(…
args)), and pass that wrapper function as a prop to your component.
const mapDispatchToProps = {
onTodoClick,
};
Back to Top
Back to Top
store = createStore(myReducer);
Back to Top
Back to Top
Back to Top
render() {
return this.props.isLoaded ? (
<div>{"Loaded"}</div>
) : (
<div>{"Not Loaded"}</div>
);
}
}
Back to Top
You need to follow two steps to use your store in your container:
i. Use mapStateToProps() : It maps the state variables from your store to the
props that you specify.
ii. Connect the above props to your container: The object returned by the
mapStateToProps function is connected to the container. You can import
connect() from react-redux .
function mapStateToProps(state) {
return { containerData: state.data };
}
Back to Top
For example, let us take rootReducer() to return the initial state after USER_LOGOUT
action. As we know, reducers are supposed to return the initial state when they are
called with undefined as the first argument, no matter the action.
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.
state = undefined;
}
Back to Top
164. 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.
Without decorator:
function mapStateToProps(state) {
return { todos: state.todos };
}
function mapDispatchToProps(dispatch) {
return { actions: bindActionCreators(actionCreators, dispatch) };
}
With decorator:
function mapStateToProps(state) {
return { todos: state.todos };
}
function mapDispatchToProps(dispatch) {
return { actions: bindActionCreators(actionCreators, dispatch) };
}
@connect(mapStateToProps, mapDispatchToProps)
export default class MyApp extends React.Component {
// ...define your main app here
}
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.
Back to Top
165. What
is the difference between React context and React
Redux?
You can use Context in your application directly and is going to be great for passing
down data to deeply nested components which what it was designed for.
Whereas Redux is much more powerful and provides a large number of features that
the Context API doesn't provide. Also, React Redux uses context internally but it
doesn't expose this fact in the public API.
Back to Top
Back to Top
Let's take an example of fetching specific account as an AJAX call using fetch API:
function setAccount(data) {
return { type: "SET_Account", data: data };
}
Back to Top
Back to Top
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).
class MyComponent {
someMethod() {
doSomethingWith(this.context.store);
}
}
Back to Top
170. What
is the difference between component and container in
React Redux?
Component is a class or function component that describes the presentational part of
your application.
Back to Top
ii. In reducers:
Let's create reducer.js :
Back to Top
Back to Top
173. What
is the use of the ownProps parameter in
mapStateToProps() and mapDispatchToProps() ?
If the ownProps parameter is specified, React Redux will pass the props that were
passed to the component into your connect functions. So, if you use a connected
component:
{
user: "john";
}
You can use this object to decide what to return from those functions.
Back to Top
This structure works well for small and medium size apps.
Back to Top
It is available in NPM:
Back to Top
Back to Top
177. What
are the differences between call() and put() in redux-
saga?
Both call() and put() are effect creator functions. call() function is used to
create effect description, which instructs middleware to call the promise. put()
function creates an effect, which instructs middleware to dispatch an action to the
store.
Let's take example of how these effects work for fetching particular user data.
function* fetchUserSaga(action) {
// `call` function accepts rest arguments, which will be passed to `api
// Instructing middleware to call promise, it resolved value will be as
const userData = yield call(api.fetchUser, action.userId);
Back to Top
178. What is Redux Thunk?
Redux Thunk middleware allows you to write action creators that return a function
instead of an action. The thunk can be used to delay the dispatch of an action, or to
dispatch only if a certain condition is met. The inner function receives the store
methods dispatch() and getState() as parameters.
Back to Top
179. What
are the differences between redux-saga and redux-
thunk ?
Both Redux Thunk and Redux Saga take care of dealing with side effects. In most of
the scenarios, Thunk uses Promises to deal with them, whereas Saga uses
Generators. Thunk is simple to use and Promises are familiar to many developers,
Sagas/Generators are more powerful but you will need to learn them. But both
middleware can coexist, so you can start with Thunks and introduce Sagas when/if
you need them.
Back to Top
Back to Top
i. The selector can compute derived data, allowing Redux to store the minimal
possible state
ii. The selector is not recomputed unless one of its arguments changes
Back to Top
Back to Top
Back to Top
Back to Top
const initialState = {
todos: [{ id: 123, name: "example", completed: false }],
};
Back to Top
For example, let's take an action which represents adding a new todo item:
{
type: ADD_TODO,
text: 'Add todo item'
}
Back to Top
React Native
Back to Top
React Native is a mobile framework that compiles to native app components, allowing
you to build native mobile applications (iOS, Android, and Windows) in JavaScript that
allows you to use React to build your components, and implements React under the
hood.
Back to Top
Back to Top
$ react-native log-ios
$ react-native log-android
Back to Top
191. How to debug your React Native?
Follow the below steps to debug React Native app:
Back to Top
Reselect keeps a copy of the last inputs/outputs of the last call, and recomputes the
result only if one of the inputs changes. If the the same inputs are provided twice in a
row, Reselect returns the cached output. It's memoization and cache are fully
customizable.
Back to Top
Back to Top
PropTypes is a basic type checker (runtime checker) which has been patched onto
React. It can't check anything other than the types of the props being passed to a
given component. If you want more flexible typechecking for your entire project
Flow/TypeScript are appropriate choices.
Back to Top
i. Install font-awesome :
import "font-awesome/css/font-awesome.min.css";
render() {
return <div><i className={'fa fa-spinner'} /></div>
}
Back to Top
i. Chrome extension
ii. Firefox extension
iii. Standalone app (Safari, React Native, etc)
Back to Top
Back to Top
<link
rel="import"
href="../../bower_components/polymer/polymer.html"
/>;
Polymer({
is: "calendar-element",
ready: function () {
this.textContent = "I am a calendar";
},
});
ii. Create the Polymer component HTML tag by importing it in a HTML document,
e.g. import it in the index.html of your React application:
<link
rel="import"
href="./src/polymer-components/calendar-element.html"
/>
Back to Top
Note: The above list of advantages are purely opinionated and it vary based on the
professional experience. But they are helpful as base parameters.
Back to Top
React Angular
React is a library and has only Angular is a framework and has complete
the View layer MVC functionality
React uses JSX that looks like Angular follows the template approach for
HTML in JS which can be HTML, which makes code shorter and easy
confusing to understand
In React, data flows only in one In Angular, data flows both way i.e it has
way and hence debugging is two-way data binding between children and
easy parent and hence debugging is often difficult
Note: The above list of differences are purely opinionated and it vary based on the
professional experience. But they are helpful as base parameters.
Back to Top
Back to Top
Back to Top
These two variables, Title and Wrapper , are now components that you can
render just like any other react component.
<Wrapper>
<Title>{"Lets start first styled component!"}</Title>
</Wrapper>
Back to Top
Back to Top
# or
But for lower versions of react scripts, just supply --scripts-version option as
react-scripts-ts while you create a new project. react-scripts-ts is a set of
adjustments to take the standard create-react-app project pipeline and bring
TypeScript into the mix.
my-app/
├─ .gitignore
├─ images.d.ts
├─ node_modules/
├─ public/
├─ src/
│ └─ ...
├─ package.json
├─ tsconfig.json
├─ tsconfig.prod.json
├─ tsconfig.test.json
└─ tslint.json
Miscellaneous
Back to Top
i. Selectors can compute derived data, allowing Redux to store the minimal
possible state.
ii. Selectors are efficient. A selector is not recomputed unless one of its arguments
changes.
iii. Selectors are composable. They can be used as input to other selectors.
Let's take calculations and different amounts of a shipment order with the simplified
usage of Reselect:
let exampleState = {
shop: {
taxPercent: 8,
items: [
{ name: "apple", value: 1.2 },
{ name: "orange", value: 0.95 },
],
},
};
console.log(subtotalSelector(exampleState)); // 2.15
console.log(taxSelector(exampleState)); // 0.172
console.log(totalSelector(exampleState)); // { total: 2.322 }
Back to Top
209. Does the statics object work with ES6 classes in React?
No, statics only works with React.createClass() :
someComponent = React.createClass({
statics: {
someMethod: function () {
// ..
},
},
});
static someMethod() {
// ...
}
}
Component.propTypes = {...}
Component.someMethod = function(){....}
Back to Top
Back to Top
Back to Top
If your initialValues prop gets updated, your form will update too.
Back to Top
213. How React PropTypes allow different types for one prop?
You can use oneOfType() method of PropTypes .
For example, the height property can be defined with either string or number type
as below:
Component.propTypes = {
size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};
Back to Top
Back to Top
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" ref={(input) => (this.input = input)} /> //
Access DOM input in handle submit
<button type="submit">Submit</button>
</form>
);
}
}
But our expectation is for the ref callback to get called once, when the component
mounts. One quick fix is to use the ES7 class property syntax to define the function
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" ref={this.setSearchInput} /> // Access DOM inp
in handle submit
<button type="submit">Submit</button>
</form>
);
}
}
Props Proxy
In this approach, the render method of the HOC returns a React Element of the type
of the WrappedComponent. We also pass through the props that the HOC receives,
hence the name Props Proxy.
function ppHOC(WrappedComponent) {
return class PP extends React.Component {
render() {
return <WrappedComponent {...this.props} />;
}
};
}
Inheritance Inversion
function iiHOC(WrappedComponent) {
return class Enhancer extends WrappedComponent {
render() {
return super.render();
}
};
}
Back to Top
React.render(
<User age={30} department={"IT"} />,
document.getElementById("container")
);
Back to Top
219. DoI need to keep all my state into Redux? Should I ever use
react internal state?
It is up to the developer's decision, i.e., it is developer's job to determine what kinds of
state make up your application, and where each piece of state should live. Some
users prefer to keep every single piece of data in Redux, to maintain a fully
serializable and controlled version of their application at all times. Others prefer to
keep non-critical or UI state, such as “is this dropdown currently open”, inside a
component's internal state.
Below are the thumb rules to determine what kind of data should be put into Redux
Back to Top
Back to Top
Back to Top
function MyComponent() {
return (
<div>
<OtherComponent />
</div>
);
}
Note: React.lazy and Suspense is not yet available for server-side rendering. If
you want to do code-splitting in a server rendered app, we still recommend React
Loadable.
Back to Top
223. How to prevent unnecessary updates using setState?
You can compare the current value of the state with an existing state value and decide
whether to rerender the page or not. If the values are the same then you need to
return null to stop re-rendering otherwise return the latest state value.
Back to Top
You can also merge this array of items in another array component.
Strings and Numbers: You can also return string and number type from the render
method.
render() {
return 'Welcome to ReactJS questions';
}
// Number
render() {
return 2018;
}
Back to Top
Let's take a counter example to demonstrate class field declarations for state without
using constructor and methods without binding,
handleIncrement = () => {
this.setState((prevState) => ({
value: prevState.value + 1,
}));
};
handleDecrement = () => {
this.setState((prevState) => ({
value: prevState.value - 1,
}));
};
render() {
return (
<div>
{this.state.value}
<button onClick={this.handleIncrement}>+</button>
<button onClick={this.handleDecrement}>-</button>
</div>
);
}
}
Back to Top
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
Back to Top
Back to Top
Back to Top
Flux Redux
The Store contains both state and The Store and change logic are
change logic separate
Flux Redux
There are multiple stores exist There is only one store exist
All the stores are disconnected and flat Single store with hierarchical reducers
Back to Top
i. In React Router v4(version 4), the API is completely about components. A router
can be visualized as a single component( <BrowserRouter> ) which wraps
specific child router components( <Route> ).
ii. You don't need to manually set history. The router module will take care history by
wrapping routes with <BrowserRouter> component.
iii. The application size is reduced by adding only the specific router module(Web,
core, or native)
Back to Top
231. Can
you describe about componentDidCatch lifecycle method
signature?
The componentDidCatch lifecycle method is invoked after an error has been thrown
by a descendant component. The method receives two parameters,
componentDidCatch(error, info);
Back to Top
232. In which scenarios error boundaries do not catch errors?
Below are the cases in which error boundaries doesn't work,
Back to Top
233. Why do you not need error boundaries for event handlers?
Error boundaries do not catch errors inside event handlers.
React doesn’t need error boundaries to recover from errors in event handlers. Unlike
the render method and lifecycle methods, the event handlers don’t happen during
rendering. So if they throw, React still knows what to display on the screen.
If you need to catch an error inside an event handler, use the regular JavaScript try /
catch statement:
handleClick() {
try {
// Do something that could throw
} catch (error) {
this.setState({ error });
}
}
render() {
if (this.state.error) {
return <h1>Caught an error.</h1>;
}
return <button onClick={this.handleClick}>Click Me</button>;
}
}
Note that the above example is demonstrating regular JavaScript behavior and
doesn’t use error boundaries.
Back to Top
234. What
is the difference between try catch block and error
boundaries?
Try catch block works with imperative code whereas error boundaries are meant for
declarative code to render on the screen.
For example, the try catch block used for below imperative code
try {
showButton();
} catch (error) {
// ...
}
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
Back to Top
Back to Top
Back to Top
237. What
is the benefit of component stack trace from error
boundary?
Apart from error messages and javascript stack, React16 will display the component
stack trace with file names and line numbers using error boundary concept.
For example, BuggyCounter component displays the component stack trace as below,
Back to Top
238. What
is the required method to be defined for a class
component?
The render() method is the only required method in a class component. i.e, All
methods other than render method are optional for a class component.
Back to Top
i. React elements: Elements that instruct React to render a DOM node. It includes
html elements such as <div/> and user defined elements.
ii. Arrays and fragments: Return multiple elements to render as Arrays and
Fragments to wrap multiple elements
iii. Portals: Render children into a different DOM subtree.
iv. String and numbers: Render both Strings and Numbers as text nodes in the
DOM
v. Booleans or null: Doesn't render anything but these types are used to
conditionally render content.
Back to Top
constructor(props) {
super(props);
// Don't call this.setState() here!
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}
Back to Top
Back to Top
For example, let us create color default prop for the button component,
MyButton.defaultProps = {
color: "red",
};
If props.color is not provided then it will set the default value to 'red'. i.e, Whenever
you try to access the color prop it uses default value
render() {
return <MyButton /> ; // props.color will be set to red
}
Back to Top
Back to Top
static getDerivedStateFromError(error)
Let us take error boundary use case with the above lifecycle method for
demonstration purpose,
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
Back to Top
i. static getDerivedStateFromProps()
ii. shouldComponentUpdate()
iii. render()
iv. getSnapshotBeforeUpdate()
v. componentDidUpdate()
Back to Top
i. static getDerivedStateFromError()
ii. componentDidCatch()
Back to Top
function withSubscription(WrappedComponent) {
class WithSubscription extends React.Component {
/* ... */
}
WithSubscription.displayName = `WithSubscription(${getDisplayName(
WrappedComponent
)})`;
return WithSubscription;
}
function getDisplayName(WrappedComponent) {
return (
WrappedComponent.displayName || WrappedComponent.name || "Component"
);
}
Back to Top
Back to Top
ReactDOM.unmountComponentAtNode(container);
Back to Top
250. What is code-splitting?
Code-Splitting is a feature supported by bundlers like Webpack and Browserify which
can create multiple bundles that can be dynamically loaded at runtime. The react
project supports code splitting via dynamic import() feature.
For example, in the below code snippets, it will make moduleA.js and all its unique
dependencies as a separate chunk that only loads after the user clicks the 'Load'
button. moduleA.js
export { moduleA };
App.js
render() {
return (
<div>
<button onClick={this.handleClick}>Load</button>
</div>
);
}
}
Back to Top
Back to Top
function Glossary(props) {
return (
<dl>
{props.items.map((item) => (
// Without the `key`, React will fire a key warning
<React.Fragment key={item.id}>
<dt>{item.term}</dt>
<dd>{item.description}</dd>
</React.Fragment>
))}
</dl>
);
}
Note: key is the only attribute that can be passed to Fragment. In the future, there
might be a support for additional attributes, such as event handlers.
Back to Top
These props work similarly to the corresponding HTML attributes, with the exception
of the special cases. It also support all SVG attributes.
Back to Top
i. Don’t use HOCs inside the render method: It is not recommended to apply a
HOC to a component within the render method of a component.
render() {
// A new version of EnhancedComponent is created on every render
// EnhancedComponent1 !== EnhancedComponent2
const EnhancedComponent = enhance(MyComponent);
// That causes the entire subtree to unmount/remount each time!
return <EnhancedComponent />;
}
ii. Static methods must be copied over: When you apply a HOC to a component
the new component does not have any of the static methods of the original
component
You can overcome this by copying the methods onto the container before
returning it,
function enhance(WrappedComponent) {
class Enhance extends React.Component {
/*...*/
}
// Must know exactly which method(s) to copy :(
Enhance.staticMethod = WrappedComponent.staticMethod;
return Enhance;
}
iii. Refs aren’t passed through: For HOCs you need to pass through all props to
the wrapped component but this does not work for refs. This is because ref is not
really a prop similar to key. In this case you need to use the React.forwardRef API
Back to Top
For example, If you don't name the render function or not using displayName property
then it will appear as ”ForwardRef” in the DevTools,
As an alternative, You can also set displayName property for forwardRef function,
function logProps(Component) {
class LogProps extends React.Component {
// ...
}
return React.forwardRef(forwardRef);
}
Back to Top
Note: It is not recommended to use this approach because it can be confused with
the ES6 object shorthand (example, {name} which is short for {name: name} )
Back to Top
i. Server-rendered by default
ii. Automatic code splitting for faster page loads
iii. Simple client-side routing (page based)
iv. Webpack-based dev environment which supports (HMR)
v. Able to implement with Express or any other Node.js HTTP server
vi. Customizable with your own Babel and Webpack configurations
Back to Top
<button onClick="{this.handleClick}"></button>
Back to Top
Note: Using an arrow function in render method creates a new function each time the
component renders, which may have performance implications
Back to Top
Back to Top
Back to Top
For example, lets take a ticking clock example, where it updates the time by calling
render method multiple times,
function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(element, document.getElementById("root"));
}
setInterval(tick, 1000);
Back to Top
The above function is called “pure” because it does not attempt to change their inputs,
and always return the same result for the same inputs. Hence, React has a single rule
saying "All React components must act like pure functions with respect to their props."
Back to Top
For example, let us take a facebook user with posts and comments details as state
variables,
constructor(props) {
super(props);
this.state = {
posts: [],
comments: []
};
}
Now you can update them independently with separate setState() calls as below,
componentDidMount() {
fetchPosts().then(response => {
this.setState({
posts: response.posts
});
});
fetchComments().then(response => {
this.setState({
comments: response.comments
});
});
}
Back to Top
Back to Top
function Greeting(props) {
if (!props.loggedIn) {
return null;
}
return <div className="greeting">welcome, {props.name}</div>;
}
render() {
return (
<div>
//Prevent component render if it is not loggedIn
<Greeting loggedIn={this.state.loggedIn} />
<UserDetails name={this.state.name}>
</div>
);
}
In the above example, the greeting component skips its rendering section by
applying condition and returning null value.
Back to Top
267. What are the conditions to safely use the index as a key?
There are three conditions to make sure, it is safe use the index as a key.
i. The list and items are static– they are not computed and do not change
ii. The items in the list have no ids
iii. The list is never reordered or filtered.
Back to Top
For example, the below Book component uses two arrays with different arrays,
function Book(props) {
const index = (
<ul>
{props.pages.map((page) => (
<li key={page.id}>{page.title}</li>
))}
</ul>
);
const content = props.pages.map((page) => (
<div key={page.id}>
<h3>{page.title}</h3>
<p>{page.content}</p>
<p>{page.pageNumber}</p>
</div>
));
return (
<div>
{index}
<hr />
{content}
</div>
);
}
Back to Top
It is used to create a scalable, performant, form helper with a minimal API to solve
annoying stuff.
Back to Top
270. What are the advantages of formik over redux form library?
Below are the main reasons to recommend formik over redux form library,
i. The form state is inherently short-term and local, so tracking it in Redux (or any
kind of Flux library) is unnecessary.
ii. Redux-Form calls your entire top-level Redux reducer multiple times ON EVERY
SINGLE KEYSTROKE. This way it increases input latency for large apps.
iii. Redux-Form is 22.5 kB minified gzipped whereas Formik is 12.7 kB
Back to Top
Back to Top
For example, let us use Vaadin date picker web component as below,
Back to Top
i. Normal Import
import("./math").then((math) => {
console.log(math.add(10, 20));
});
Back to Top
function MyComponent() {
return (
<div>
<OtherComponent />
</div>
);
}
Back to Top
function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
</div>
);
}
As mentioned in the above code, Suspense is wrapped above the lazy component.
Back to Top
Let us take an example of route based website using libraries like React Router with
React.lazy,
In the above code, the code splitting will happen at each route level.
Back to Top
For example, in the code below lets manually thread through a “theme” prop in order
to style the Button component.
Back to Top
278. What is the purpose of default value in context?
The defaultValue argument is only used when a component does not have a matching
Provider above it in the tree. This can be helpful for testing components in isolation
without wrapping them.
Back to Top
ii. Static field You can use a static class field to initialize your contextType using
public class field syntax.
Back to Top
<MyContext.Consumer>
{value => /* render something based on the context value */}
</MyContext.Consumer>
Back to Top
281. How
do you solve performance corner cases while using
context?
The context uses reference identity to determine when to re-render, there are some
gotchas that could trigger unintentional renders in consumers when a provider’s
parent re-renders.
For example, the code below will re-render all consumers every time the Provider re-
renders because a new object is always created for value.
class App extends React.Component {
render() {
return (
<Provider value={{ something: "something" }}>
<Toolbar />
</Provider>
);
}
}
render() {
return (
<Provider value={this.state.value}>
<Toolbar />
</Provider>
);
}
}
Back to Top
function logProps(Component) {
class LogProps extends React.Component {
componentDidUpdate(prevProps) {
console.log("old props:", prevProps);
console.log("new props:", this.props);
}
render() {
const { forwardedRef, ...rest } = this.props;
Let's use this HOC to log all props that get passed to our “fancy button” component,
// ...
}
export default logProps(FancyButton);
Now let's create a ref and pass it to FancyButton component. In this case, you can set
focus to button element.
Back to Top
284. Why do you need additional care for component libraries while
using forward refs?
When you start using forwardRef in a component library, you should treat it as a
breaking change and release a new major version of your library. This is because your
library likely has a different behavior such as what refs get assigned to, and what
types are exported. These changes can break apps and other libraries that depend on
the old behavior.
Back to Top
Note: If you use createReactClass then auto binding is available for all methods. i.e,
You don't need to use .bind(this) with in constructor for event handlers.
Back to Top
ReactDOM.render(
<Greeting message="World" />,
document.getElementById("root")
);
ReactDOM.render(
React.createElement(Greeting, { message: "World" }, null),
document.getElementById("root")
);
Back to Top
In this case, displaying 1000 elements would require in the order of one billion
comparisons. This is far too expensive. Instead, React implements a heuristic O(n)
algorithm based on two assumptions:
i. Two elements of different types will produce different trees.
ii. The developer can hint at which child elements may be stable across different
renders with a key prop.
Back to Top
i. Elements Of Different Types: Whenever the root elements have different types,
React will tear down the old tree and build the new tree from scratch. For
example, elements to , or from
ii. DOM Elements Of The Same Type: When comparing two React DOM elements
of the same type, React looks at the attributes of both, keeps the same
underlying DOM node, and only updates the changed attributes. Lets take an
example with same DOM elements except className attribute,
iii. Component Elements Of The Same Type: When a component updates, the
instance stays the same, so that state is maintained across renders. React
updates the props of the underlying component instance to match the new
element, and calls componentWillReceiveProps() and componentWillUpdate() on
the underlying instance. After that, the render() method is called and the diff
algorithm recurses on the previous result and the new result.
iv. Recursing On Children: when recursing on the children of a DOM node, React
just iterates over both lists of children at the same time and generates a mutation
whenever there’s a difference. For example, when adding an element at the end
of the children, converting between these two trees works well.
<ul>
<li>first</li>
<li>second</li>
</ul>
<ul>
<li>first</li>
<li>second</li>
<li>third</li>
</ul>
v. Handling keys: React supports a key attribute. When children have keys, React
uses the key to match children in the original tree with children in the subsequent
tree. For example, adding a key can make the tree conversion efficient,
<ul>
<li key="2015">Duke</li>
<li key="2016">Villanova</li>
</ul>
<ul>
<li key="2014">Connecticut</li>
<li key="2015">Duke</li>
<li key="2016">Villanova</li>
</ul>
Back to Top
Back to Top
<Mouse
children={(mouse) => (
<p>
The mouse position is {mouse.x}, {mouse.y}
</p>
)}
/>
Actually children prop doesn’t need to be named in the list of “attributes” in JSX
element. Instead, you can keep it directly inside element,
<Mouse>
{(mouse) => (
<p>
The mouse position is {mouse.x}, {mouse.y}
</p>
)}
</Mouse>
While using this above technique(without any name), explicitly state that children
should be a function in your propTypes.
Mouse.propTypes = {
children: PropTypes.func.isRequired,
};
Back to Top
291. What
are the problems of using render props with pure
components?
If you create a function inside a render method, it negates the purpose of pure
component. Because the shallow prop comparison will always return false for new
props, and each render in this case will generate a new value for the render prop. You
can solve this issue by defining the render function as instance method.
Back to Top
This way render props gives the flexibility of using either pattern.
Back to Top
Back to Top
Back to Top
Back to Top
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
User Name:
<input
defaultValue="John"
type="text"
ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
The same applies for select and textArea inputs. But you need to use
defaultChecked for checkbox and radio inputs.
Back to Top
Back to Top
298. What is the difference between Real DOM and Virtual DOM?
Below are the main differences between Real DOM and Virtual DOM,
You can update HTML directly. You Can’t directly update HTML
Creates a new DOM if element updates It updates the JSX if element update
Back to Top
i. Using the Bootstrap CDN: This is the easiest way to add bootstrap. Add both
bootstrap CSS and JS resources in a head tag.
ii. Bootstrap as Dependency: If you are using a build tool or a module bundler such
as Webpack, then this is the preferred option for adding Bootstrap to your React
application
iii. React Bootstrap Package: In this case, you can add Bootstrap to our React app
is by using a package that has rebuilt Bootstrap components to work particularly
as React components. Below packages are popular in this category,
a. react-bootstrap
b. reactstrap
Back to Top
i. Facebook
ii. Uber
iii. Instagram
iv. WhatsApp
v. Khan Academy
vi. Airbnb
vii. Dropbox
viii. Flipboard
ix. Netflix
x. PayPal
Back to Top
Back to Top
Back to Top
Here is an example of fetching a list of react articles from an API using fetch.
function App() {
const [data, setData] = React.useState({ hits: [] });
React.useEffect(() => {
fetch("http://hn.algolia.com/api/v1/search?query=react")
.then(response => response.json())
.then(data => setData(data))
}, []);
return (
<ul>
{data.hits.map((item) => (
<li key={item.objectID}>
<a href={item.url}>{item.title}</a>
</li>
))}
</ul>
);
}
Back to Top
Back to Top
i. React DOM
ii. React DOM Server
iii. React Test Renderer
iv. React Shallow Renderer
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
310. What
are typical middleware choices for handling
asynchronous calls in Redux?
Some of the popular middleware choices for handling asynchronous calls in Redux
eco system are Redux Thunk, Redux Promise, Redux Saga .
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
Back to Top
There is only one large There is more than one store for
Data Store
store exist for data storage storage
Back to Top
// in es 5
var someData = this.props.someData;
var dispatch = this.props.dispatch;
// in es6
const { someData, dispatch } = this.props;
// in es 5
<SomeComponent someData={this.props.someData} dispatch={this.props.di
// in es6
<SomeComponent {...this.props} />
Back to Top
Back to Top
320. What
is the difference between async mode and concurrent
mode?
Both refers the same thing. Previously concurrent Mode being referred to as "Async
Mode" by React team. The name has been changed to highlight React’s ability to
perform work on different priority levels. So it avoids the confusion from other
approaches to Async Rendering.
Back to Top
const companyProfile = {
website: "javascript: alert('Your website is hacked')",
};
// It will log a warning
<a href={companyProfile.website}>More details</a>;
Remember that the future versions will throw an error for javascript URLs.
Back to Top
Back to Top
323. What
is the difference between Imperative and Declarative in
React?
Imagine a simple UI component, such as a "Like" button. When you tap it, it turns blue
if it was previously grey, and grey if it was previously blue.
if (user.likes()) {
if (hasBlue()) {
removeBlue();
addGrey();
} else {
removeGrey();
addBlue();
}
}
Basically, you have to check what is currently on the screen and handle all the
changes necessary to redraw it with the current state, including undoing the changes
from the previous state. You can imagine how complex this could be in a real-world
scenario.
if (this.state.liked) {
return <blueLike />;
} else {
return <greyLike />;
}
Because the declarative approach separates concerns, this part of it only needs to
handle how the UI should look in a sepecific state, and is therefore much simpler to
understand.
Back to Top
Back to Top
325. Howdo you make sure that user remains authenticated on page
refresh while using Context API State Management?
When a user logs in and reload, to persist the state generally we add the load user
action in the useEffect hooks in the main App.js. While using Redux, loadUser action
can be easily accessed.
App.js
index.js
ReactDOM.render(
<React.StrictMode>
<AuthState>
<App />
</AuthState>
</React.StrictMode>,
document.getElementById("root")
);
App.js
useEffect(() => {
loadUser();
}, []);
loadUser
if (!token) {
dispatch({
type: ERROR,
});
}
setAuthToken(token);
try {
const res = await axios("/api/auth");
dispatch({
type: USER_LOADED,
payload: res.data.data,
});
} catch (err) {
console.error(err);
}
};
Back to Top
Back to Top
327. How is the new JSX transform different from old transform??
The new JSX transform doesn’t require React to be in scope. i.e, You don't need to
import React package for simple scenarios.
Let's take an example to look at the main differences between the old and the new
transform,
Old Transform:
function App() {
return <h1>Good morning!!</h1>;
}
Now JSX transform convert the above code into regular JavaScript as below,
function App() {
return React.createElement("h1", null, "Good morning!!");
}
New Transform:
function App() {
return <h1>Good morning!!</h1>;
}
function App() {
return _jsx("h1", { children: "Good morning!!" });
}
Back to Top
Note: React Server Components is still under development and not recommended for
production yet.
Back to Top
Back to Top
This can cause unknown issues in the UI as the value of the state variable got
updated without telling React to check what all components were being affected from
this update and it can cause UI bugs.
Ex:
componentDidMount() {
let { loading } = this.state;
loading = (() => true)(); // Trying to perform an operation and directl
}
How to prevent it: Make sure your state variables are immutable by either enforcing
immutability by using plugins like Immutable.js, always using setState to make
updates, and returning new instances in reducers when sending updated state values.
Back to Top
Back to Top
We can create a wrapper component that will add a border to the message
component:
Wrapper component can also accept its own props and pass them down to the
wrapped component, for example, we can create a wrapper component that will add a
title to the message component:
Now we can use the MessageWrapperWithTitle component and pass title props:
This way, the wrapper component can add additional functionality, styling, or layout to
the wrapped component while keeping the wrapped component simple and reusable.
Back to Top
334. What
are the differences between useEffect and
useLayoutEffect hooks?
useEffect and useLayoutEffect are both React hooks that can be used to synchronize
a component with an external system, such as a browser API or a third-party library.
However, there are some key differences between the two:
Timing: useEffect runs after the browser has finished painting, while
useLayoutEffect runs synchronously before the browser paints. This means that
useLayoutEffect can be used to measure and update layout in a way that feels
more synchronous to the user.
Browser Paint: useEffect allows browser to paint the changes before running the
effect, hence it may cause some visual flicker. useLayoutEffect synchronously
runs the effect before browser paints and hence it will avoid visual flicker.
Execution Order: The order in which multiple useEffect hooks are executed is
determined by React and may not be predictable. However, the order in which
multiple useLayoutEffect hooks are executed is determined by the order in which
they were called.
Error handling: useEffect has a built-in mechanism for handling errors that occur
during the execution of the effect, so that it does not crash the entire application.
useLayoutEffect does not have this mechanism, and errors that occur during the
execution of the effect will crash the entire application.
Back to Top
335. What
are the differences between Functional and Class
Components?
There are two different ways to create components in ReactJS. The main differences
are listed down as below,
1. Syntax:
The classs components uses ES6 classes to create the components. It uses render
function to display the HTML content in the webpage.
Functional component has been improved over the years with some added features
like Hooks. Here is a syntax for functional component.
function App(){
return <div className="App">
<h1>Hello, I'm a function component</h1>
</div>
}
2. State:
State contains information or data about a component which may change over time.
In class component, you can update the state when a user interacts with it or server
updates the data using the setState() method. The initial state is going to be
assigned in the Constructor( ) method using the the this.state object and it
is possible to different data types in the this.state object such as string, boolean,
numbers, etc. A simple example showing how we use the setState() and
constructor()
You not use state in functional components because it was only supported in
class components. But over the years hooks have been implemented in
functional component which enable to use state in functional component too.
function App() {
const [message, setMessage] = useState("This is a functional
component");
const updateMessage = () => {
setCountry("Updating the functional component");
};
return (
<div className="App">
<h1>{message} </h1>
<button onClick={updateMessage}>Click me!!</button>
</div>
);
}
4. Props:
Props are referred to as "properties". The props are passed into react
component just like arguments passed to a function. In otherwords, they are
similar to HTML attributes.
Props in functional components are similar to that of the class components but
the difference is the absence of 'this' keyword.
function Child(props) {
return <h1>This is a child component and the component name
is{props.name}</h1>;
}
function Parent() {
return (
<div className="Parent">
<Child name="First child component" />
<Child name="Second child component" />
</div>
);
}
Back to Top
Disclaimer
The questions provided in this repository are the summary of frequently asked
questions across numerous companies. We cannot guarantee that these questions
will actually be asked during your interview process, nor should you focus on
memorizing all of them. The primary purpose is for you to get a sense of what some
companies might ask — do not get discouraged if you don't know the answer to all
of them — that is ok!
Releases
No releases published
Packages
No packages published
Contributors 84
+ 73 contributors
Languages