React Interview Queations
React Interview Queations
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?
No. Questions
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 make
127
an AJAX call?
React Router
135 Why you get "Router may have only one child element" warning?
React Internationalization
React Testing
React Redux
No. Questions
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?
213 How React PropTypes allow different type for one prop?
219 Do I need to keep all my state into Redux? Should I ever use react internal 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?
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?
No. Questions
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?
310 What are typical middleware choices for handling asynchronous calls in Redux?
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 does new JSX transform different from old transform?
Core React
1. What is React?
React is an open-source frontend JavaScript library which 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.
class App extends React.Component {
render() {
return(
<div>
<h1>{'Welcome to React world!'}</h1>
</div>
)
}
}
An Element is a plain object describing what you want to appear on the screen in terms of
the DOM nodes or other components. Elements can contain other Elements in their props.
Creating a React element is cheap. Once an element is created, it is never mutated.
The object representation of React Element would be as follows:
const element = React.createElement(
'div',
{id: 'login-btn'},
'Login'
)
The above React.createElement() function returns an object:
{
type: 'div',
props: {
children: 'Login',
id: 'login-btn'
}
}
And finally it renders to the DOM using ReactDOM.render():
<div id='login-btn'>Login</div>
Whereas a component can be declared in several different ways. It can be a class with
a render() method. Alternatively, in simple cases, it can be defined as a function. In either
case, it takes props as an input, and returns a JSX tree as the output:
const Button = ({ onLogin }) =>
<div id={'login-btn'} onClick={onLogin}>Login</div>
Then JSX gets transpiled to a React.createElement() function tree:
const Button = ({ onLogin }) => React.createElement(
'div',
{ id: 'login-btn', onClick: onLogin },
'Login'
)
this.state = {
message: 'Welcome to React world'
}
}
render() {
return (
<div>
<h1>{this.state.message}</h1>
</div>
)
}
}
State is similar to props, but it is private and fully controlled by the component. i.e, It is not
accessible to any component other than the one that owns and sets it.
Instead use setState() method. It schedules an update to a component's state object. When
state changes, the component responds by re-rendering.
//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.
13. What is the difference between HTML and React event handling?
Below are some of the main differences between HTML and React event handling,
i. In HTML, the event name usually represents in lowercase as a convention:
<button onclick='activateLasers()'>
Whereas in React it follows camelCase convention:
<button onClick={activateLasers}>
ii. In HTML, you can return false to prevent default behavior:
<a href='#' onclick='console.log("The link was clicked."); return false;' />
Whereas in React you must call preventDefault() explicitly:
function handleClick(event) {
event.preventDefault()
console.log('The link was clicked.')
}
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)
xiv. Arrow functions in callbacks: You can use arrow functions directly in the
callbacks.
xv. <button onClick={(event) => this.handleClick(event)}>
xvi. {'Click me'}
</button>
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.
You can use either if statements or ternary expressions which are available from JS to
conditionally render expressions. Apart from these approaches, you can also embed any
expressions in JSX by wrapping them in curly braces and then followed by JS logical
operator &&.
<h1>Hello!</h1>
{
messages.length > 0 && !isLogin?
<h2>
You have {messages.length} unread messages.
</h2>
:
<h2>
You don't have unread messages.
</h2>
}
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:
const todoItems = todos.map((todo) =>
<li key={todo.id}>
{todo.text}
</li>
)
When you don't have stable IDs for rendered items, you may use the item index as a key as a
last resort:
const todoItems = todos.map((todo, index) =>
<li key={index}>
{todo.text}
</li>
)
Note:
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.
The ref is used to return a reference to the element. They should be avoided in most cases,
however, they can be useful when you need a direct access to the DOM element or an
instance of a component.
render() {
return <div ref={this.node} />
}
}
The Virtual DOM (VDOM) is an in-memory representation of Real DOM. The representation
of a UI is kept in memory and synced with the "real" DOM. It's a step that happens between
the render function being called and the displaying of elements on the screen. This entire
process is called reconciliation.
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.
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.
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>
);
}
}
In most cases, it's recommend to use controlled components to implement forms.
When several components need to share the same changing data then it is recommended
to lift the shared state up to their closest common ancestor. That means if two child
components share the same data from its parent, then move the state to parent instead of
maintaining local state in both of the child components.
iii. Unmounting: In this last phase, the component is not needed and get
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
iv. Render The component will render without any side-effects. This applies for
Pure components and in this phase, React can pause, abort, or restart the
render.
v. 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().
vi. Commit React works with the DOM and executes the final lifecycles
respectively componentDidMount() for mounting, componentDidUpdate() for
updating, and componentWillUnmount() for unmounting.
React 16.3+ Phases (or an interactive version)
Before React 16.3
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.
const EnhancedComponent = higherOrderComponent(WrappedComponent)
HOC can be used for many use cases:
i. Code reuse, logic and bootstrap abstraction.
ii. Render hijacking.
iii. State abstraction and manipulation.
iv. Props manipulation.
Children is a prop (this.props.children) that allow you to pass components as data to other
components, just like any other prop you use. Component tree put between component's
opening and closing tag will be passed to that component as children prop.
There are a number of methods available in the React API to work with this prop. These
include React.Children.map, React.Children.forEach, React.Children.count, React.Children.on
ly, React.Children.toArray.
A simple usage of children prop looks as below,
const MyDiv = React.createClass({
render: function() {
return <div>{this.props.children}</div>
}
})
ReactDOM.render(
<MyDiv>
<span>{'Hello'}</span>
<span>{'World'}</span>
</MyDiv>,
node
)
40. What is the purpose of using super constructor with props argument?
A child class constructor cannot make use of this reference until super() method has been
called. The same applies for ES6 sub-classes as well. The main reason of passing props
parameter to super() call is to access this.props in your child constructors.
Passing props:
class MyComponent extends React.Component {
constructor(props) {
super(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.
If you are using ES6 or the Babel transpiler to transform your JSX code then you can
accomplish this with computed property names.
handleInputChange(event) {
this.setState({ [event.target.id]: event.target.value })
}
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>
}
Instead, pass the function itself without parenthesis:
render() {
// Correct: handleClick is passed as a reference!
return <button onClick={this.handleClick}>{'Click Me'}</button>
}
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>
}
If the behaviour is independent of its state then it can be a stateless component. You can use
either a function or a class for creating stateless components. But unless you need to use a
lifecycle hook in your components, you should go for function components. There are a lot
of benefits if you decide to use function components here; they are easy to write,
understand, and test, a little faster, and you can avoid the this keyword altogether.
return (
// JSX
)
}
render() {
return (
<>
<h1>{`Welcome, ${this.props.name}`}</h1>
<h2>{`Age, ${this.props.age}`}</h2>
</>
)
}
}
Note: In React v15.5 PropTypes were moved from React.PropTypes to prop-types library.
The Equivalent Functional Component
import React from 'react'
import PropTypes from 'prop-types'
function User() {
return (
<>
<h1>{`Welcome, ${this.props.name}`}</h1>
<h2>{`Age, ${this.props.age}`}</h2>
</>
)
}
User.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired
}
iii. Integrating React into a traditional MVC framework requires some additional
configuration.
iv. The code complexity increases with inline templating and JSX.
v. Too many smaller components leading to over engineering or boilerplate.
54. What are error boundaries in React v16?
Error boundaries are components that catch JavaScript errors anywhere in their child
component tree, log those errors, and display a fallback UI instead of the component tree
that crashed.
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
}
}
After that use it as a regular component:
<ErrorBoundary>
<MyWidget />
</ErrorBoundary>
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.
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()
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.
ReactDOM.render(element, container[, callback])
If the optional callback is provided, it will be executed after the component is rendered or
updated.
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'
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />
}
The style attribute accepts a JavaScript object with camelCased properties rather than a CSS
string. This is consistent with the DOM style JavaScript property, is more efficient, and
prevents XSS security holes.
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).
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.
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} />
)}
If the props on the component are changed without the component being refreshed, the
new prop value will never be displayed because the constructor function will never update
the current state of the component. The initialization of state from props only runs when the
component is first created.
The below component won't display the updated input value:
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
records: [],
inputValue: this.props.inputValue
};
}
render() {
return <div>{this.state.inputValue}</div>
}
}
Using props inside render method will update the value:
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
record: []
}
}
render() {
return <div>{this.props.inputValue}</div>
}
}
In some cases you want to render different components depending on some state. JSX does
not render false or undefined, so you can use conditional short-circuiting to render a given
part of your component only if a certain condition is true.
const MyComponent = ({ name, address }) => (
<div>
<h2>{name}</h2>
{address &&
<p>{address}</p>
}
</div>
)
If you need an if-else condition then use ternary operator.
const MyComponent = ({ name, address }) => (
<div>
<h2>{name}</h2>
{address
? <p>{address}</p>
: <p>{'Address is not available'}</p>
}
</div>
)
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,
const ComponentA = () =>
<ComponentB isDisplay={true} className={'componentStyle'} />
You can decorate your class components, which is the same as passing the component into a
function. Decorators are flexible and readable way of modifying component functionality.
@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.
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.
You should use Webpack's DefinePlugin method to set NODE_ENV to production, by which it
strip out things like propType validation and extra warnings. Apart from this, if you minify
the code, for example, Uglify's dead-code elimination to strip out development only code
and comments, it will drastically reduce the size of your bundle.
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.
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.
This lifecycle method along with componentDidUpdate() covers all the use cases
of componentWillReceiveProps().
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().
class MyComponent extends React.Component {
getSnapshotBeforeUpdate(prevProps, prevState) {
// ...
}
}
This lifecycle method along with componentDidUpdate() covers all the use cases
of componentWillUpdate().
Both render props and higher-order components render only a single child but in most of
the cases Hooks are a simpler way to serve this by reducing nesting in your tree.
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 dev-time errors.
Page.propTypes = {
page: PropTypes.oneOf(Object.keys(PAGES)).isRequired
}
React may batch multiple setState() calls into a single update for performance.
Because this.props and this.state may be updated asynchronously, you should not rely on
their values for calculating the next state.
This counter example will fail to update as expected:
// 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
}))
function ExampleApplication() {
return (
<div>
<Header />
<React.StrictMode>
<div>
<ComponentOne />
<ComponentTwo />
</div>
</React.StrictMode>
<Footer />
</div>
)
}
The component names should start with a uppercase letter but there are few exceptions on
this convention. The lowercase tag names with a dot (property accessors) are still considered
as valid component names.
```jsx harmony
render(){
return (
<obj.component /> // `React.createElement(obj.component)`
)
}
```
This is useful for supplying browser-specific non-standard attributes, trying new DOM APIs,
and integrating with opinionated third-party libraries.
You should initialize state in the constructor when using ES6 classes,
and getInitialState() method when using React.createClass().
Using ES6 classes:
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = { /* initial state */ }
}
}
Using React.createClass():
const MyComponent = React.createClass({
getInitialState() {
return { /* initial state */ }
}
})
Note: React.createClass() is deprecated and removed in React v16. Use plain JavaScript
classes instead.
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():
class MyComponent extends React.Component {
constructor(props) {
super()
console.log(this.props) // undefined
}
}
Outside constructor() both will display same value for this.props.
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.
React (or JSX) doesn't support variable interpolation inside an attribute value. The below
representation won't work:
<img className='image' src='images/{this.props.image}' />
But you can put any JS expression inside curly braces as the entire attribute value. So the
below expression works:
<img className='image' src={'images/' + this.props.image} />
Using template strings will also work:
<img className='image' src={`images/${this.props.image}`} />
94. What is React proptype array with shape?
If you want to pass an array of objects to a component with a particular shape then
use React.PropTypes.shape() as an argument to React.PropTypes.arrayOf().
ReactComponent.propTypes = {
arrayWithShape: React.PropTypes.arrayOf(React.PropTypes.shape({
color: React.PropTypes.string.isRequired,
fontSize: React.PropTypes.number.isRequired
})).isRequired
}
Instead you need to move curly braces outside (don't forget to include spaces between class
names):
<div className={'btn-panel ' + (this.props.visible ? 'show' : 'hidden')}>
Template strings will also work:
<div className={`btn-panel ${this.props.visible ? 'show' : 'hidden'}`}>
The React team worked on extracting all DOM-related features into a separate library
called ReactDOM. React v0.14 is the first release in which the libraries are split. By looking at
some of the packages, react-native, react-art, react-canvas, and react-three, it has become
clear that the beauty and essence of React has nothing to do with browsers or the DOM.
To build more environments that React can render to, React team planned to split the main
React package into two: react and react-dom. This paves the way to writing components that
can be shared between the web version of React and React Native.
If you try to render a <label> element bound to a text input using the standard for attribute,
then it produces HTML missing that attribute and prints a warning to the console.
<label for={'user'}>{'User'}</label>
<input type={'text'} id={'user'} />
Since for is a reserved keyword in JavaScript, use htmlFor instead.
<label htmlFor={'user'}>{'User'}</label>
<input type={'text'} id={'user'} />
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>
}
}
The React philosophy is that props should be immutable and top-down. This means that a
parent can send any prop values to a child, but the child can't modify received props.
render() {
return (
<div>
<input
defaultValue={'Won\'t focus'}
/>
<input
ref={(input) => this.nameInput = input}
defaultValue={'Will focus'}
/>
</div>
)
}
}
ReactDOM.render(
<div>{`React version: ${REACT_VERSION}`}</div>,
document.getElementById('app')
)
You just need to use HTTPS=true configuration. You can edit your package.json scripts
section:
"scripts": {
"start": "set HTTPS=true && react-scripts start"
}
or just run set HTTPS=true && npm start
After that restart the development server. Now you should be able to import anything
inside src/app without relative paths.
You need to use setInterval() to trigger the change, but you also need to clear the timer
when the component unmounts to prevent errors and memory leaks.
componentDidMount() {
this.interval = setInterval(() => this.setState({ time: Date.now() }), 1000)
}
componentWillUnmount() {
clearInterval(this.interval)
}
117. How to import and export components using React and ES6?
You should use default for exporting the components
import React from 'react'
import User from 'user'
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:
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 <div>Error: {error.message}</div>;
} else {
return (
<ul>
{employees.map(employee => (
<li key={employee.name}>
{employee.name}-{employee.experience}
</li>
))}
</ul>
)
}
}
}
Render Props is a simple technique for sharing code between components using a prop
whose value is a function. The below component uses render prop which returns a React
element.
<DataProvider render={data => (
<h1>{`Hello ${data.target}`}</h1>
)}/>
Libraries such as React Router and DownShift are using this pattern.
React Router
React Router is a powerful routing library built on top of React that helps you add new
screens and flows to your application incredibly quickly, all while keeping the URL in sync
with what's being displayed on the page.
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.
import { withRouter } from 'react-router-dom' // this also works with 'react-router-native'
The <Route> component passes the same props as withRouter(), so you will be able to
access the history methods through the history prop.
import { Route } from 'react-router-dom'
Button.contextTypes = {
history: React.PropTypes.shape({
push: React.PropTypes.func.isRequired
})
}
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:
import { Switch, Router, Route } from 'react-router'
Then define the routes within <Switch> block:
<Router>
<Switch>
<Route {/* ... */} />
<Route {/* ... */} />
</Switch>
</Router>
i. Create a module that exports a history object and import this module across
the project.
For example, create history.js file:
import { createBrowserHistory } from 'history'
xi. You can also use push method of history object similar to built-in history
object:
xii. // some-other-file.js
xiii. import history from './history'
xiv.
history.push('/go-here')
139. How to perform automatic redirect after login?
The react-router package provides <Redirect> component in React Router. Rendering
a <Redirect> will navigate to a new location. Like server-side redirects, the new location will
override the current location in the history stack.
import React, { Component } from 'react'
import { Redirect } from 'react-router'
MyComponent.propTypes = {
intl: intlShape.isRequired
}
MyComponent.propTypes = {
intl: intlShape.isRequired
}
The injectIntl() higher-order component will give you access to the formatDate() method via
the props in your component. The method is used internally by instances
of FormattedDate and it returns the string representation of the formatted date.
import { injectIntl, intlShape } from 'react-intl'
MyComponent.propTypes = {
intl: intlShape.isRequired
}
Shallow rendering is useful for writing unit test cases in React. It lets you render a
component one level deep and assert facts about what its render method returns, without
worrying about the behavior of child components, which are not instantiated or rendered.
For example, if you have the following component:
function MyComponent() {
return (
<div>
<span className={'heading'}>{'Title'}</span>
<span className={'description'}>{'Description'}</span>
</div>
)
}
Then you can assert as follows:
import ShallowRenderer from 'react-test-renderer/shallow'
// 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>
])
console.log(testRenderer.toJSON())
// {
// type: 'a',
// props: { href: 'https://www.facebook.com/' },
// children: [ 'Facebook' ]
// }
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:
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.
ii. You're going to have to carefully pick your packages: While Flux explicitly
doesn't try to solve problems such as undo/redo, persistence, or forms,
Redux has extension points such as middleware and store enhancers, and it
has spawned a rich ecosystem.
iii. There is no nice Flow integration yet: Flux currently lets you do very
impressive static type checks which Redux doesn't support yet.
mapStateToProps() is a utility which helps your component get updated state (which is
updated by some other components):
const mapStateToProps = (state) => {
return {
todos: getVisibleTodos(state.todos, state.visibilityFilter)
}
}
mapDispatchToProps() is a utility which will help your component to fire an action event
(dispatching action which may cause change of application state):
const mapDispatchToProps = (dispatch) => {
return {
onTodoClick: (id) => {
dispatch(toggleTodo(id))
}
}
}
Recommend always using the “object shorthand” form for the mapDispatchToProps
Redux wrap 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
})
You just need to export the store from the module where it created with createStore(). Also,
it shouldn't pollute the global window object.
store = createStore(myReducer)
iv. No way to do undo (travel back in time) easily without adding so much extra
code.
Redux is a tool for managing state throughout the application. It is usually used as an
architecture for UIs. Think of it as an alternative to (half of) Angular. RxJS is a reactive
programming library. It is usually used as a tool to accomplish asynchronous tasks in
JavaScript. Think of it as an alternative to Promises. Redux uses the Reactive paradigm
because the Store is reactive. The Store observes actions from a distance, and changes itself.
RxJS also uses the Reactive paradigm, but instead of being an architecture, it gives you basic
building blocks, Observables, to accomplish this pattern.
render() {
return this.props.isLoaded
? <div>{'Loaded'}</div>
: <div>{'Not Loaded'}</div>
}
}
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.
iii. import React from 'react'
iv. import { connect } from 'react-redux'
v.
vi. class App extends React.Component {
vii. render() {
viii. return <div>{this.props.containerData}</div>
ix. }
x. }
xi.
xii. function mapStateToProps(state) {
xiii. return { containerData: state.data }
xiv. }
xv.
export default connect(mapStateToProps)(App)
state = undefined
}
o function mapStateToProps(state) {
o return { todos: state.todos }
o }
o
o function mapDispatchToProps(dispatch) {
o return { actions: bindActionCreators(actionCreators, dispatch) }
o }
o
o function mapStateToProps(state) {
o return { todos: state.todos }
o }
o
o function mapDispatchToProps(dispatch) {
o return { actions: bindActionCreators(actionCreators, dispatch) }
o }
o
o @connect(mapStateToProps, mapDispatchToProps)
o export default class MyApp extends React.Component {
o // ...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.
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.
Reducers always return the accumulation of the state (based on all previous and current
actions). Therefore, they act as a reducer of state. Each time a Redux reducer is called, the
state and action are passed as parameters. This state is then reduced (or accumulated)
based on the action, and then the next state is returned. You could reduce a collection of
actions and an initial state (of the store) on which to perform these actions to get the
resulting final state.
function setAccount(data) {
return { type: 'SET_Account', data: data }
}
Saga is like a separate thread in your application, that's solely responsible for side
effects. redux-saga is a redux middleware, which means this thread can be started, paused
and cancelled from the main application with normal Redux actions, it has access to the full
Redux application state and it can dispatch Redux actions as well.
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.fetchUser` function.
// Instructing middleware to call promise, it resolved value will be assigned to `userData`
variable
const userData = yield call(api.fetchUser, action.userId)
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.
Redux DevTools is a live-editing time travel environment for Redux with hot reloading, action
replay, and customizable UI. If you don't want to bother with installing Redux DevTools and
integrating it into your project, consider using Redux DevTools Extension for Chrome and
Firefox.
iv. If the reducers throw, you will see during which action this happened, and
what the error was.
v. With persistState() store enhancer, you can persist debug sessions across
page reloads.
Selectors are functions that take Redux state as an argument and return some data to pass
to the component.
For example, to get user details from the state:
const getUserData = state => state.user.data
These selectors have two main benefits,
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
For example, you can add redux-thunk and logger passing them as arguments
to applyMiddleware():
import { createStore, applyMiddleware } from 'redux'
const createStoreWithMiddleware = applyMiddleware(ReduxThunk, logger)(createStore)
const initialState = {
todos: [{ id: 123, name: 'example', completed: false }]
}
Relay is similar to Redux in that they both use a single store. The main difference is that relay
only manages state originated from the server, and all access to the state is used
via GraphQL queries (for reading data) and mutations (for changing data). Relay caches the
data for you and optimizes data fetching for you, by fetching only changed data and nothing
more.
188. What is an action in Redux?
Actions are plain JavaScript objects or payloads of information that send data from your
application to your store. They are the only source of information for the store. Actions must
have a type property that indicates the type of action being performed.
For example, let's take an action which represents adding a new todo item:
{
type: ADD_TODO,
text: 'Add todo item'
}
React Native
React is a JavaScript library, supporting both front end web and being run on the server, for
building user interfaces and web applications.
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.
React Native can be tested only in mobile simulators like iOS and Android. You can run the
app in your mobile using expo app (https://expo.io) Where it syncs using QR code, your
mobile and computer should be in same wireless network.
Reselect is a selector library (for Redux) which uses memoization concept. It was originally
written to compute derived data from Redux-like applications state, but it can't be tied to
any architecture or library.
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.
Flow is a static analysis tool (static checker) which uses a superset of the language, allowing
you to add type annotations to all of your code and catch an entire class of bugs at compile
time.
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.
React Developer Tools let you inspect the component hierarchy, including component props
and state. It exists both as a browser extension (for Chrome and Firefox), and as a
standalone app (works with other environments including Safari, IE, and React Native).
The official extensions available for different browsers or environments.
i. Chrome extension
ii. Firefox extension
iii. Standalone app (Safari, React Native, etc)
If you opened a local HTML file in your browser (file://...) then you must first open Chrome
Extensions and check Allow access to file URLs.
Note: The above list of advantages are purely opinionated and it vary based on the
professional experience. But they are helpful as base parameters.
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
Note: The above list of differences are purely opinionated and it vary based on the
professional experience. But they are helpful as base parameters.
// Create a <Title> component that renders an <h1> which is centered, red and sized at
1.5em
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`
// Create a <Wrapper> component that renders a <section> with some padding and a
papayawhip background
const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`
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>
Relay is a JavaScript framework for providing a data layer and client-server communication
to web applications using the React view layer.
# or
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.
207. Give an example of Reselect usage?
Let's take calculations and different amounts of a shipment order with the simplified usage
of Reselect:
import { createSelector } from 'reselect'
let exampleState = {
shop: {
taxPercent: 8,
items: [
{ name: 'apple', value: 1.20 },
{ name: 'orange', value: 0.95 },
]
}
}
console.log(subtotalSelector(exampleState)) // 2.15
console.log(taxSelector(exampleState)) // 0.172
console.log(totalSelector(exampleState)) // { total: 2.322 }
209. Does the statics object work with ES6 classes in React?
No, statics only works with React.createClass():
someComponent= React.createClass({
statics: {
someMethod: function() {
// ..
}
}
})
But you can write statics inside ES6+ classes as below,
class Component extends React.Component {
static propTypes = {
// ...
}
static someMethod() {
// ...
}
}
or writing them outside class as below,
class Component extends React.Component {
....
}
Component.propTypes = {...}
Component.someMethod = function(){....}
Redux can be used as a data store for any UI layer. The most common usage is with React
and React Native, but there are bindings available for Angular, Angular 2, Vue, Mithril, and
more. Redux simply provides a subscription mechanism which can be used by any other
code.
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
])
}
If the ref callback is defined as an inline function, it will get called twice during updates, first
with null and then again with the DOM element. This is because a new instance of the
function is created with each render, so React needs to clear the old ref and set up the new
one.
class UserForm extends Component {
handleSubmit = () => {
console.log("Input Value is: ", this.input.value)
}
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
class UserForm extends Component {
handleSubmit = () => {
console.log("Input Value is: ", this.input.value)
}
render () {
return (
<form onSubmit={this.handleSubmit}>
<input
type='text'
ref={this.setSearchInput} /> // Access DOM input in handle submit
<button type='submit'>Submit</button>
</form>
)
}
}
**Note:** In React v16.3,
219. Do I need to keep all my state into Redux? Should I ever use react internal
state?
It is up to developer decision. i.e, It is developer 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
i. Do other parts of the application care about this data?
ii. Do you need to be able to create further derived data based on this original
data?
iii. Is the same data being used to drive multiple components?
iv. Is there value to you in being able to restore this state to a given point in time
(ie, time travel debugging)?
v. Do you want to cache the data (i.e, use what's in state if it's already there
instead of re-requesting it)?
React creates a service worker for you without any configuration by default. The service
worker is a web API that helps you cache your assets and other files so that when the user is
offline or on slow network, he/she can still see results on the screen, as such, it helps you
build a better user experience, that's what you should know about service worker's for now.
It's all about adding offline capabilities to your site.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
Class components can be restricted from rendering when their input props are the same
using PureComponent or shouldComponentUpdate. Now you can do the same with
function components by wrapping them in React.memo.
const MyComponent = React.memo(function MyComponent(props) {
/* only rerenders if props change */
});
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.
224. How do you render Array, Strings and Numbers in React 16 Version?
Arrays: Unlike older releases, you don't need to make sure render method return a single
element in React16. You are able to return multiple sibling elements without a wrapping
element by returning an array.
For example, let us take the below list of developers,
const ReactJSDevs = () => {
return [
<li key="1">John</li>,
<li key="2">Jackie</li>,
<li key="3">Jordan</li>
];
}
You can also merge this array of items in another array component.
const JSDevs = () => {
return (
<ul>
<li>Brad</li>
<li>Brodge</li>
<ReactJSDevs/>
<li>Brandon</li>
</ul>
);
}
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;
}
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>
)
}
}
Hooks is a new feature(React 16.8) that lets you use state and other React features without
writing a class.
Let's see an example of useState hook example,
import { useState } from 'react';
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>
);
}
ii. Call Hooks from React Functions only. i.e, You shouldn’t call Hooks from
regular JavaScript functions.
React team released an ESLint plugin called eslint-plugin-react-hooks that enforces these
two rules. You can add this plugin to your project using the below command,
npm install eslint-plugin-react-hooks@next
And apply the below config in your ESLint config file,
// Your ESLint configuration
{
"plugins": [
// ...
"react-hooks"
],
"rules": {
// ...
"react-hooks/rules-of-hooks": "error"
}
}
Note: This plugin is intended to use in Create React App by default.
Flux Redux
The Store contains both state and The Store and change logic are
change logic separate
There are multiple stores exist There is only one store exist
All the stores are disconnected and flat Single store with hierarchical reducers
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)
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:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { error: null };
this.handleClick = this.handleClick.bind(this);
}
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.
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) {
// ...
}
Whereas error boundaries wrap declarative code as below,
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
So if an error occurs in a componentDidUpdate method caused by a setState somewhere
deep in the tree, it will still correctly propagate to the closest error boundary.
The granularity of error boundaries usage is up to the developer based on project needs. You
can follow either of these approaches,
i. You can wrap top-level route components to display a generic error message
for the entire application.
ii. You can also wrap individual components in an error boundary to protect
them from crashing the rest of the application.
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,
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.
ii. For binding event handler methods to the instance For example, the below
code covers both the above cases,
constructor(props) {
super(props);
// Don't call this.setState() here!
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}
No, it is not mandatory. i.e, If you don’t initialize state and you don’t bind methods, you
don’t need to implement a constructor for your React component.
The defaultProps are defined as a property on the component class to set the default props
for the class. This is used for undefined props, but not for null props.
For example, let us create color default prop for the button component,
class MyButton extends React.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
}
Note: If you provide null value then it remains null value.
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;
}
}
For example, To ease debugging, choose a display name that communicates that it’s the
result of a withSubscription HOC.
function withSubscription(WrappedComponent) {
class WithSubscription extends React.Component {/* ... */}
WithSubscription.displayName =
`WithSubscription(${getDisplayName(WrappedComponent)})`;
return WithSubscription;
}
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
export { moduleA };
App.js
import React, { Component } from 'react';
render() {
return (
<div>
<button onClick={this.handleClick}>Load</button>
</div>
);
}
}
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.
ii. render() {
iii. // A new version of EnhancedComponent is created on every render
iv. // EnhancedComponent1 !== EnhancedComponent2
v. const EnhancedComponent = enhance(MyComponent);
vi. // That causes the entire subtree to unmount/remount each time!
vii. return <EnhancedComponent />;
}
The above code impact performance by remounting a component that causes the state of
that component and all of its children to be lost. Instead, apply HOCs outside the component
definition so that the resulting component is created only once.
viii. 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
ix. // Define a static method
x. WrappedComponent.staticMethod = function() {/*...*/}
xi. // Now apply a HOC
xii. const EnhancedComponent = enhance(WrappedComponent);
xiii.
xiv. // The enhanced component has no static method
typeof EnhancedComponent.staticMethod === 'undefined' // true
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;
}
xv. 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
For example, If you don't name the render function or not using displayName property then
it will appear as ”ForwardRef” in the DevTools,
const WrappedComponent = React.forwardRef((props, ref) => {
return <LogProps {...props} forwardedRef={ref} />;
});
But If you name the render function then it will appear as ”ForwardRef(myFunction)”
const WrappedComponent = React.forwardRef(
function myFunction(props, ref) {
return <LogProps {...props} forwardedRef={ref} />;
}
);
As an alternative, You can also set displayName property for forwardRef function,
function logProps(Component) {
class LogProps extends React.Component {
// ...
}
return React.forwardRef(forwardRef);
}
If you pass no value for a prop, it defaults to true. This behavior is available so that it
matches the behavior of HTML.
For example, below expressions are equivalent,
<MyInput autocomplete />
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})
You can pass event handlers and other functions as props to child components. It can be
used in child component as below,
<button onClick={this.handleClick}>
React DOM escapes any values embedded in JSX before rendering them. Thus it ensures that
you can never inject anything that’s not explicitly written in your application. Everything is
converted to a string before being rendered.
For example, you can embed user input as below,
const name = response.potentiallyMaliciousInput;
const element = <h1>{name}</h1>;
This way you can prevent XSS(Cross-site-scripting) attacks in the application.
setInterval(tick, 1000);
263. How do you say that props are read only?
When you declare a component as a function or a class, it must never modify its own props.
Let us take a below capital function,
function capital(amount, interest) {
return amount + interest;
}
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."
fetchComments().then(response => {
this.setState({
comments: response.comments
});
});
}
As mentioned in the above code snippets, this.setState({comments}) updates only
comments variable without modifying or replacing posts variable.
return (
<div className="greeting">
welcome, {props.name}
</div>
);
}
class User extends React.Component {
constructor(props) {
super(props);
this.state = {loggedIn: false, name: 'John'};
}
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.
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.
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
The dynamic import() syntax is a ECMAScript proposal not currently part of the language
standard. It is expected to be accepted in the near future. You can achieve code-splitting into
your app using dynamic import.
Let's take an example of addition,
i. Normal Import
import { add } from './math';
console.log(add(10, 20));
ii. Dynamic Import
import("./math").then(math => {
console.log(math.add(10, 20));
});
function MyComponent() {
return (
<div>
<OtherComponent />
</div>
)
}
Now OtherComponent will be loaded in a separated bundle
If the module containing the dynamic import is not yet loaded by the time parent
component renders, you must show some fallback content while you’re waiting for it to load
using a loading indicator. This can be done using Suspense component.
For example, the below code uses suspense component,
const OtherComponent = React.lazy(() => import('./OtherComponent'));
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.
One of the best place to do code splitting is with routes. The entire page is going to re-
render at once so users are unlikely to interact with other elements in the page at the same
time. Due to this, the user experience won't be disturbed.
Let us take an example of route based website using libraries like React Router with
React.lazy,
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import React, { Suspense, lazy } from 'react';
ContextType is used to consume the context object. The contextType property can be used
in two ways,
i. contextType as property of class: The contextType property on a class can be
assigned a Context object created by React.createContext(). After that, you
can consume the nearest current value of that Context type using this.context
in any of the lifecycle methods and render function.
Lets assign contextType property on MyClass as below,
class MyClass extends React.Component {
componentDidMount() {
let value = this.context;
/* perform a side-effect at mount using the value of MyContext */
}
componentDidUpdate() {
let value = this.context;
/* ... */
}
componentWillUnmount() {
let value = this.context;
/* ... */
}
render() {
let value = this.context;
/* render something based on the value of MyContext */
}
}
MyClass.contextType = MyContext;
ii. Static field You can use a static class field to initialize your contextType using
public class field syntax.
iii. class MyClass extends React.Component {
iv. static contextType = MyContext;
v. render() {
vi. let value = this.context;
vii. /* render something based on the value */
viii. }
}
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>
);
}
}
This can be solved by lifting up the value to parent state,
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
value: {something: 'something'},
};
}
render() {
return (
<Provider value={this.state.value}>
<Toolbar />
</Provider>
);
}
}
render() {
const {forwardedRef, ...rest} = this.props;
// Assign the custom prop "forwardedRef" as a ref
return <Component ref={forwardedRef} {...rest} />;
}
}
// ...
}
export default logProps(FancyButton);
Now lets create a ref and pass it to FancyButton component. In this case, you can set focus
to button element.
import FancyButton from './FancyButton';
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.
ReactDOM.render(
<Greeting message="World" />,
document.getElementById('root')
);
You can write the same code without JSX as below,
class Greeting extends React.Component {
render() {
return React.createElement('div', null, `Hello ${this.props.message}`);
}
}
ReactDOM.render(
React.createElement(Greeting, {message: 'World'}, null),
document.getElementById('root')
);
287. What is diffing algorithm?
React needs to use algorithms to find out how to efficiently update the UI to match the most
recent tree. The diffing algorithms is generating the minimum number of operations to
transform one tree into another. However, the algorithms have a complexity in the order of
O(n3) where n is the number of elements in the tree.
In this case, for 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.
When diffing two trees, React first compares the two root elements. The behavior is
different depending on the types of the root elements. It covers the below rules during
reconciliation algorithm,
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.
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. <div className="show" title="ReactJS" />
iv.
<div className="hide" title="ReactJS" />
<ul>
<li key="2014">Connecticut</li>
<li key="2015">Duke</li>
<li key="2016">Villanova</li>
</ul>
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
};
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.
The same applies for select and textArea inputs. But you need to
use defaultChecked for checkbox and radio inputs.
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
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
npm install bootstrap
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
300. Can you list down top websites or applications using react as front end
framework?
Below are the top 10 websites using React as their front-end framework,
i. Facebook
ii. Uber
iii. Instagram
iv. WhatsApp
v. Khan Academy
vi. Airbnb
vii. Dropbox
viii. Flipboard
ix. Netflix
x. PayPal
useEffect(async () => {
const result = await axios(
'http://hn.algolia.com/api/v1/search?query=react',
);
setData(result.data);
}, []);
return (
<ul>
{data.hits.map(item => (
<li key={item.objectID}>
<a href={item.url}>{item.title}</a>
</li>
))}
</ul>
);
}
Hooks doesn't cover all use cases of classes but there is a plan to add them soon. Currently
there are no Hook equivalents to the
uncommon getSnapshotBeforeUpdate and componentDidCatch lifecycles yet.
305. What is the stable release for hooks support?
React includes a stable implementation of React Hooks in 16.8 release for below packages
i. React DOM
ii. React DOM Server
iii. React Test Renderer
iv. React Shallow Renderer
When we declare a state variable with useState, it returns a pair — an array with two items.
The first item is the current value, and the second is a function that updates the value. Using
[0] and [1] to access them is a bit confusing because they have a specific meaning. This is
why we use array destructuring instead.
For example, the array index access would look as follows:
var userStateVariable = useState('userProfile'); // Returns an array pair
var user = userStateVariable[0]; // Access first item
var setUser = userStateVariable[1]; // Access second item
Whereas with array destructuring the variables can be accessed as follows:
const [user, setUser] = useState('userProfile');
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.
The react-scripts package is a set of scripts from the create-react-app starter pack which
helps you kick off projects without configuring. The react-scripts start command sets up the
development environment and starts a server, as well as hot module reloading.
vi. A build script to bundle JS, CSS, and images for production, with hashes and
sourcemaps
vii. An offline-first service worker and a web app manifest, meeting all the
Progressive Web App criteria.
There is only one large There is more than one store for
Data Store
store exist for data storage storage
No, you don’t have to learn es2015/es6 to learn react. But you may find many resources or
React ecosystem uses ES6 extensively. Let's see some of the frequently used ES6 features,
i. Destructuring: To get props and use them in a component
ii. // in es 5
iii. var someData = this.props.someData
iv. var dispatch = this.props.dispatch
v.
vi. // in es6
const { someData, dispatch } = this.props
vii. Spread operator: Helps in passing props down into a component
viii. // in es 5
ix. <SomeComponent someData={this.props.someData}
dispatch={this.props.dispatch} />
x.
xi. // in es6
<SomeComponent {...this.props} />
xii. Arrow functions: Makes compact syntax
xiii. // es 5
xiv. var users = usersList.map(function (user) {
xv. return <li>{user.name}</li>
xvi. })
xvii. // es 6
const users = usersList.map(user => <li>{user.name}</li>);
319. What is Concurrent Rendering?
The Concurrent rendering makes React apps to be more responsive by rendering component
trees without blocking the main UI thread. It allows React to interrupt a long-running render
to handle a high-priority event. i.e, When you enabled concurrent Mode, React will keep an
eye on other tasks that need to be done, and if there's something with a higher priority it
will pause what it is currently rendering and let the other task finish first. You can enable this
in two ways,
// 1. Part of an app by wrapping with ConcurrentMode
<React.unstable_ConcurrentMode>
<Something />
</React.unstable_ConcurrentMode>
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.
Yes, you can use javascript: URLs but it will log a warning in the console. Because URLs
starting with javascript: are dangerous by including unsanitized output in a tag like <a
href> and create a security hole.
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.
322. What is the purpose of eslint plugin for hooks?
The ESLint plugin enforces rules of Hooks to avoid bugs. It assumes that any function starting
with ”use” and a capital letter right after it is a Hook. In particular, the rule enforces that,
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.
The imperative way of doing this would be:
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.
In contrast, the declarative approach would be:
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.
324. What are the benefits of using typescript with reactjs?
Below are some of the benefits of using typescript with Reactjs,
i. It is possible to use latest JavaScript features
ii. Use of interfaces for complex type definitions
iii. IDEs such as VS Code was made for TypeScript
iv. Avoid bugs with the ease of readability and Validation
325. How do 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
import {loadUser} from '../actions/auth';
store.dispatch(loadUser());
But while using Context API, to access context in App.js, wrap the AuthState in
index.js so that App.js can access the auth context. Now whenever the page reloads,
no matter what route you are on, the user will be authenticated as loadUser action
will be triggered on each re-render.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import AuthState from './context/auth/AuthState'
ReactDOM.render(
<React.StrictMode>
<AuthState>
<App />
</AuthState>
</React.StrictMode>,
document.getElementById('root')
);
App.js
const authContext = useContext(AuthContext);
useEffect(() => {
loadUser();
},[])
loadUser
const loadUser = async () => {
const token = sessionStorage.getItem('token');
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);
}
}
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:
import React from 'react';
function App() {
return <h1>Good morning!!</h1>;
}
Now JSX transform convert the above code into regular JavaScript as below,
import React from 'react';
function App() {
return React.createElement('h1', null, 'Good morning!!');
}
New Transform:
The new JSX transform doesn't require any React imports
function App() {
return <h1>Good morning!!</h1>;
}
Under the hood JSX transform compiles to below code
import {jsx as _jsx} from 'react/jsx-runtime';
function App() {
return _jsx('h1', { children: 'Good morning!!' });
}
Note: You still need to import React to use Hooks.
328. How do you get redux scaffolding using create-react-app?
Redux team has provided official redux+js or redux+typescript templates for create-react-
app project. The generated project setup includes,
i. Redux Toolkit and React-Redux dependencies
ii. Create and configure Redux store
iii. React-Redux <Provider> passing the store to React components
iv. Small "counter" example to demo how to add redux logic and React-Redux
hooks API to interact with the store from components
The below commands need to be executed along with template option as below,
v. Javascript template:
npx create-react-app my-app --template redux
ii. Typescript template:
npx create-react-app my-app --template redux-typescript
329. What are React Server components?
React Server Component is a way to write React component that gets rendered in the
server-side with the purpose of improving React app performance. These components allow
us to load components from the backend.
Note: React Server Components is still under development and not recommended for
production yet.
330. What is prop drilling?
Prop Drilling is the process by which you pass data from one component of the React
Component tree to another by going through other components that do not need the data
but only help in passing it around.
331. What are the different ways to prevent state mutation?