Sudheerj - Reactjs-Interview-Questions - List of Top 500 ReactJS Interview Questions & Answers.... Coding Exercise Questions Are Coming Soon!!
Sudheerj - Reactjs-Interview-Questions - List of Top 500 ReactJS Interview Questions & Answers.... Coding Exercise Questions Are Coming Soon!!
sudheerj /
reactjs-interview-questions
List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are coming soon!!
Public repository
1. I recommend this React course if you’re serious about learning React and want to go beyond the basics
2. Want to ace your coding interview and get hired at your dream company? Take this coding interview bootcamp
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?
https://github.com/sudheerj/reactjs-interview-questions 1/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
No. Questions
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?
43 What would be the common mistake of function being called every time the component renders?
https://github.com/sudheerj/reactjs-interview-questions 2/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
No. Questions
59 What is ReactDOMServer?
https://github.com/sudheerj/reactjs-interview-questions 3/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
No. Questions
91 What is the difference between super() and super(props) in React using ES6 classes?
103 What is the recommended approach of removing an array element in react state?
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?
127 How to make AJAX call and In which component lifecycle methods should I make an AJAX call?
React Router
https://github.com/sudheerj/reactjs-interview-questions 4/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
No. Questions
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?
https://github.com/sudheerj/reactjs-interview-questions 5/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
No. Questions
170 What is the difference between component and container in React Redux?
173 What is the use of the ownProps parameter in mapStateToProps() and mapDispatchToProps()?
177 What are the differences between call and put in redux-saga
React Native
https://github.com/sudheerj/reactjs-interview-questions 6/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
No. Questions
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?
https://github.com/sudheerj/reactjs-interview-questions 7/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
No. Questions
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?
284 Why do you need additional care for component libraries while using forward refs?
https://github.com/sudheerj/reactjs-interview-questions 8/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
No. Questions
291 What are the problems of using render props with pure components?
298 What is the difference between Real DOM and Virtual DOM?
300 Can you list down top websites or applications using react as front end framework?
310 What are typical middleware choices for handling asynchronous calls in Redux?
320
README What is the difference between async mode and concurrent mode?
325 How do you make sure that user remains authenticated on page refresh while using Context API State Management?
327 How is the new JSX transform different from old transform?
https://github.com/sudheerj/reactjs-interview-questions 9/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
No. Questions
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(aka React.js or ReactJS) is an open-source front-end JavaScript library that is used for building composable user interfaces,
especially for single-page applications. It is used for handling view layer for web and mobile apps based on components in a declarative
approach.
React was created by Jordan Walke, a software engineer working for Facebook. React was first deployed on Facebook's News Feed in 201
and on Instagram in 2012.
⬆ Back to Top
The main principle of this extension was to make front-end code easier to understand and to help avoid cross-site scripting attacks. The
project was successful to prevent the malicious content submitted by the scrubbing user.
But there was a different problem with XHP in which dynamic web applications require many roundtrips to the server, and XHP did not
solve this problem. Also, the whole UI was re-rendered for small change in the application. Later, the initial prototype of React is created
with the name FaxJ by Jordan inspired from XHP. Finally after sometime React has been introduced as a new library into JavaScript world.
⬆ Back to Top
Uses JSX syntax, a syntax extension of JS that allows developers to write HTML in their JS code.
It uses Virtual DOM instead of Real DOM considering that Real DOM manipulations are expensive.
Supports server-side rendering which is useful for Search Engine Optimizations(SEO).
Follows Unidirectional or one-way data flow or data binding.
Uses reusable/composable UI components to develop the view.
⬆ Back to Top
4. What is JSX?
JSX stands for JavaScript XML and it is an XML-like syntax extension to ECMAScript. Basically it just provides the syntactic sugar for the
React.createElement(type, props, ...children) function, giving us expressiveness of JavaScript along with HTML like template syntax.
In the example below, the text inside <h1> tag is returned as JavaScript function to the render function.
https://github.com/sudheerj/reactjs-interview-questions 10/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
);
}
If you don't use JSX syntax then the respective JavaScript code should be written as below,
See Class
⬆ Back to Top
<div id="login-btn">Login</div>
{
type: 'div',
props: {
children: 'Login',
id: 'login-btn'
}
}
Whereas a component can be declared in several different ways. It can be a class with a render() method or it can be defined as a
function. In either case, it takes props as an input, and returns a JSX tree as the output:
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 11/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
Components are the building blocks of creating User Interfaces(UI) in React. There are two possible ways to create a component.
i. Function Components: This is the simplest way to create a component. Those are pure JavaScript functions that accept props object
as the first parameter and return React elements to render the output:
ii. Class Components: You can also use ES6 class to define a component. The above function component can be written as a class
component:
⬆ Back to Top
But even there are two reasons to use Class components over Function components.
i. If you need a React functionality whose Function component equivalent is not present yet, like Error Boundaries.
ii. In older versions, If the component needs state or lifecycle methods then you need to use class component.
Note: You can also use reusable react error boundary third-party component without writing any class. i.e, No need to use class
components for Error boundaries.
The usage of Error boundaries from the above library is quite straight forward.
Note when using react-error-boundary: ErrorBoundary is a client component. You can only pass props to it that are serializeable or
use it in files that have a "use client"; directive.
"use client";
⬆ Back to Top
But at the same time, it won't compare the previous state with the current state because function component itself prevents the
unnecessary rendering by default when you set the same state again.
Below is the example of how child component(i.e., EmployeeProfile) prevents re-renders for the same props passed by parent
component(i.e.,EmployeeRegForm).
https://github.com/sudheerj/reactjs-interview-questions 12/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
<p>Name:{name}</p>
<p>Email: {email}</p>
</>);
});
export default function EmployeeRegForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
return (
<>
<label>
Name: <input value={name} onChange={e => setName(e.target.value)} />
</label>
<label>
Email: <input value={email} onChange={e => setEmail(e.target.value)} />
</label>
<hr/>
<EmployeeProfile name={name}/>
</>
);
}
In the above code, the email prop has not been passed to child component. So there won't be any re-renders for email prop change.
In class components, the components extending React.PureComponent instead of React.Component become the pure components. When
props or state changes, PureComponent will do a shallow comparison on both props and state by invoking shouldComponentUpdate()
lifecycle method.
⬆ Back to Top
Let's take an example of User component with message state. Here, useState hook has been used to add state to the User component an
it returns an array with current state and function to update it.
function User() {
const [message, setMessage] = useState("Welcome to React world");
return (
<div>
<h1>{message}</h1>
</div>
);
}
https://github.com/sudheerj/reactjs-interview-questions 13/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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) attribute 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
For example, the usage of props in function component looks like below:
The properties from props object can be accessed directly using destructing feature from ES6 (ECMAScript 2015). The above child component
can be simplified like below.
See Class
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 14/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
In React, both state and props are plain JavaScript objects and used to manage the data of a component, but they are used in differen
ways and have different characteristics. state is managed by the component itself and can be updated using the setState() function.
Unlike props, state can be modified by the component and is used to manage the internal state of the component. Changes in the state
trigger a re-render of the component and its children. props (short for "properties") are passed to a component by its parent componen
and are read-only , meaning that they cannot be modified by the component itself. props can be used to configure the behavior of a
component and to pass data between components.
⬆ Back to Top
//Wrong
this.state.message = "Hello world";
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.
⬆ Back to Top
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;'
/>
function handleClick(event) {
event.preventDefault();
console.log("The link was clicked.");
}
https://github.com/sudheerj/reactjs-interview-questions 15/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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
i. Binding in Constructor: In JavaScript classes, the methods are not bound by default. The same rule applies for React event handlers
defined as class methods. Normally we bind them in constructor.
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
The Create React App enables this syntax by default.
handleClick = () => {
console.log("SingOut triggered", this);
};
<button onClick={this.handleClick}>SingOut</button>
iii. Arrow functions in callbacks: It is possible to use arrow functions directly in the callbacks.
handleClick() {
console.log('SingOut triggered');
}
render() {
return <button onClick={() => this.handleClick()}>SignOut</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.
⬆ 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
https://github.com/sudheerj/reactjs-interview-questions 16/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
Let's take an example of BookStore title search component with the ability to get all native event properties
function BookStore() {
handleTitleChange(e) {
console.log('The new title is:', e.target.value);
// 'e' represents synthetic event
const nativeEvent = e.nativeEvent;
console.log(nativeEvent);
e.stopPropogation();
e.preventDefault();
}
⬆ 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. What is "key" prop and what is the benefit of using it in arrays of elements?
A key is a special attribute you should include when mapping over arrays to render data. 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:
Note:
i. Using indexes for keys is not recommended if the order of items may change. This can negatively impact performance and may caus
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.
iv. The key attribute accepts either string or number and internally convert it as string type.
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 17/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
⬆ Back to Top
i. This is a recently added approach. Refs are created using React.createRef() method and attached to React elements via the ref
attribute. In order to use refs throughout the component, just assign the ref to the instance property within constructor.
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,
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
https://github.com/sudheerj/reactjs-interview-questions 18/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
render() {
return <div />;
}
}
render() {
return <div ref={this.node} />;
}
}
⬆ Back to Top
i. They force React to keep track of currently executing component. This is problematic because it makes react module stateful, and thus
causes weird errors when react module is duplicated in the bundle.
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
https://github.com/sudheerj/reactjs-interview-questions 19/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
i. Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representation.
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
https://github.com/sudheerj/reactjs-interview-questions 20/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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>
);
}
}
In most cases, it's recommend to use controlled components to implement forms. In a controlled component, form data is handled by a
React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 21/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
⬆ Back to Top
⬆ Back to Top
i. Mounting: The component is ready to mount in the browser DOM. This phase covers initialization from constructor() ,
getDerivedStateFromProps() , render() , and componentDidMount() lifecycle methods.
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.
https://github.com/sudheerj/reactjs-interview-questions 22/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
⬆ Back to Top
componentWillMount: Executed before rendering and is used for App level configuration in your root component.
componentDidMount: Executed after first rendering and here all AJAX requests, DOM or state updates, and set up event listeners
should occur.
componentWillReceiveProps: Executed when particular prop updates to trigger state transitions.
shouldComponentUpdate: Determines if the component will be updated or not. By default it returns true . If you are sure that the
component doesn't need to render after state or props are updated, you can return false value. It is a great place to improve
performance as it allows you to prevent a re-render if component receives new prop.
componentWillUpdate: Executed before re-rendering the component when there are props & state changes confirmed by
shouldComponentUpdate() which returns true.
componentDidUpdate: Mostly it is used to update the DOM in response to prop or state changes.
componentWillUnmount: It will be used to cancel any outgoing network requests, or remove all event listeners associated with the
component.
React 16.3+
getDerivedStateFromProps: Invoked right before calling render() and is invoked on every render. This exists for rare use cases whe
you need a derived state. Worth reading if you need derived state.
componentDidMount: Executed after first rendering and where all AJAX requests, DOM or state updates, and set up event listeners
should occur.
shouldComponentUpdate: Determines if the component will be updated or not. By default, it returns true . If you are sure that the
component doesn't need to render after the state or props are updated, you can return a false value. It is a great place to improve
performance as it allows you to prevent a re-render if component receives a new prop.
getSnapshotBeforeUpdate: Executed right before rendered output is committed to the DOM. Any value returned by this will be
passed into componentDidUpdate() . This is useful to capture information from the DOM i.e. scroll position.
componentDidUpdate: Mostly it is used to update the DOM in response to prop or state changes. This will not fire if
shouldComponentUpdate() returns false .
componentWillUnmount It will be used to cancel any outgoing network requests, or remove all event listeners associated with the
component.
⬆ 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.
https://github.com/sudheerj/reactjs-interview-questions 23/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
⬆ 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
For example, authenticated users, locale preferences, UI themes need to be accessed in the application by many components.
⬆ 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
https://github.com/sudheerj/reactjs-interview-questions 24/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
The comments in React/JSX are similar to JavaScript Multiline comments but are wrapped in curly braces.
Single-line comments:
<div>
{/* Single-line comments(In vanilla JavaScript, the single-line comments are represented by double slash(//)) */}
{`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
https://github.com/sudheerj/reactjs-interview-questions 25/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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
The attribute class is a keyword in JavaScript, and JSX is an extension of JavaScript. That's the principle reason why React uses classNam
instead of class . Pass a string as the className prop.
render() {
return <span className={'menu navigation-menu'}>{'Menu'}</span>
}
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 26/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
It is also possible to render list of fragments inside a loop with the mandatory key attribute supplied.
function StoryBook() {
return stories.map(story =>
<Fragment key={ story.id}>
<h2>{story.title}</h2>
<p>{story.description}</p>
<p>{story.date}</p>
</Fragment>
);
}
Ususally you don't need to use until unless there is a need of key attribute. The usage of shorter syntax looks like below.
⬆ Back to Top
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 ha
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
https://github.com/sudheerj/reactjs-interview-questions 27/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
If the behaviour of a component is dependent on the state of the component then it can be termed as stateful component. These stateful
components are either function components with hooks or class components.
Let's take an example of function stateful component which update the state based on click event,
return (
<>
<button onClick={handleIncrement}>Increment</button>
<span>Counter: {count}</span>
</>
)
}
See Class
⬆ 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>
</>
);
}
}
Note: In React v15.5 PropTypes were moved from React.PropTypes to prop-types library.
https://github.com/sudheerj/reactjs-interview-questions 28/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
User.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
};
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
A class component becomes an error boundary if it defines a new lifecycle method called componentDidCatch(error, info) or static
getDerivedStateFromError() :
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>;
https://github.com/sudheerj/reactjs-interview-questions 29/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
}
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 a
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 th
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";
https://github.com/sudheerj/reactjs-interview-questions 30/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
app.get("/", (req, res) => {
res.write(
"<!DOCTYPE html><html><head><title>My Page</title></head><body>"
);
res.write('<div id="content">');
res.write(renderToString(<MyPage />));
res.write("</div></body></html>");
res.end();
});
⬆ Back to Top
In this example MyComponent uses dangerouslySetInnerHTML attribute for setting HTML markup:
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
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.
https://github.com/sudheerj/reactjs-interview-questions 31/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
{
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 withou
needing to reevaluate them as much.
{
todos.map((todo) => <Todo {...todo} key={todo.id} />);
}
⬆ Back to Top
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>;
https://github.com/sudheerj/reactjs-interview-questions 32/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
}
}
⬆ Back to Top
⬆ Back to Top
For example,
⬆ Back to Top
@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} />;
}
https://github.com/sudheerj/reactjs-interview-questions 33/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
};
};
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.
Update: Since React v16.6.0, we have a React.memo . It provides a higher order component which memoizes component unless the props
change. To use it, simply wrap the component using React.memo before you use it.
⬆ 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
https://github.com/sudheerj/reactjs-interview-questions 34/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
$ cd todo-app
⬆ Back to Top
i. constructor()
ii. static getDerivedStateFromProps()
iii. render()
iv. componentDidMount()
⬆ Back to Top
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.
⬆ Back to Top
This lifecycle method along with componentDidUpdate() covers all the use cases of componentWillReceiveProps() .
⬆ Back to Top
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() .
https://github.com/sudheerj/reactjs-interview-questions 35/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
⬆ Back to Top
⬆ Back to Top
also
⬆ Back to Top
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()
xii. getter methods for render like getSelectReason() or getFooterContent()
xiii. optional render methods like renderNavigation() or renderProfilePicture()
xiv. render()
⬆ Back to Top
For example, a switching component to display different pages based on page prop:
https://github.com/sudheerj/reactjs-interview-questions 36/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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,
};
⬆ 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)
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.
// 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
https://github.com/sudheerj/reactjs-interview-questions 37/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
Mixins are a way to totally separate components to have a common functionality. Mixins should not be used and can be replaced with
higher-order components or decorators.
One of the most commonly used mixins is PureRenderMixin . You might be using it in some components to prevent unnecessary re-rende
when the props and state are shallowly equal to the previous props and state:
⬆ Back to Top
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:
https://github.com/sudheerj/reactjs-interview-questions 38/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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() :
https://github.com/sudheerj/reactjs-interview-questions 39/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
Note: React.createClass() is deprecated and removed in React v16. Use plain JavaScript classes instead.
⬆ Back to Top
component.forceUpdate(callback);
It is recommended to avoid all uses of forceUpdate() and only read from this.props and this.state in render() .
⬆ Back to Top
90. 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) :
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>
https://github.com/sudheerj/reactjs-interview-questions 40/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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
Instead you need to move curly braces outside (don't forget to include spaces between class names):
⬆ Back to Top
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 41/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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.
⬆ 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
useEffect(() => {
function handleResize() {
setDimensions({
width: window.innerWidth,
height: window.innerHeight,
});
}
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return (
<span>
{dimensions.width} x {dimensions.height}
</span>
https://github.com/sudheerj/reactjs-interview-questions 42/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
);
}
⬆ Back to Top
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
Note: The previous releases of ReactJS also uses componentWillUpdate(object nextProps, object nextState) for state changes. It has bee
deprecated in latest releases.
⬆ Back to Top
103. What is the recommended approach of removing an array element in React state?
The better approach is to use Array.prototype.filter() method.
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 false
}
render() {
return true
}
render() {
return null
}
render() {
return []
}
https://github.com/sudheerj/reactjs-interview-questions 43/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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>
);
}
}
https://github.com/sudheerj/reactjs-interview-questions 44/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
Also in Functional component (react 16.08 and above)
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
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.
https://github.com/sudheerj/reactjs-interview-questions 45/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
import "core-js/fn/array/find";
import "core-js/fn/array/includes";
import "core-js/fn/number/is-nan";
Use the polyfill.io CDN to retrieve custom, browser-specific polyfills by adding this line to index.html :
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=default,Array.prototype.includes"></script>
In the above script we had to explicitly request the Array.prototype.includes feature as it is not included in the default feature set.
⬆ 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() }), 1000)
}
componentWillUnmount() {
clearInterval(this.interval)
}
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 46/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
<div
style={{
transform: "rotate(90deg)",
WebkitTransform: "rotate(90deg)", // note the capital 'W' here
msTransform: "rotate(90deg)", // 'ms' is the only lowercase vendor prefix
}}
/>
⬆ 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
https://github.com/sudheerj/reactjs-interview-questions 47/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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
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
https://github.com/sudheerj/reactjs-interview-questions 48/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
⬆ Back to Top
Another popular plugin is eslint-plugin-jsx-a11y , which will help fix common issues with accessibility. As JSX offers slightly different
syntax to regular HTML, issues with alt text and tabindex , for example, will not be picked up by regular plugins.
⬆ 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.
https://github.com/sudheerj/reactjs-interview-questions 49/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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 th
history instance associated with your router available through the context in the router object.
⬆ Back to Top
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.
https://github.com/sudheerj/reactjs-interview-questions 50/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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>
https://github.com/sudheerj/reactjs-interview-questions 51/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
<Route {/* ... */} />
<Route {/* ... */} />
</Switch>
</Router>
⬆ Back to Top
this.props.history.push({
pathname: "/template",
search: "?name=sudheer",
state: { detail: response.data },
});
⬆ Back to Top
<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
https://github.com/sudheerj/reactjs-interview-questions 52/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
React Internationalization
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
<FormattedMessage
id={"account"}
defaultMessage={"The amount is less than minimum balance."}
/>
formatMessage(messages.accountMessage);
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 53/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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
https://github.com/sudheerj/reactjs-interview-questions 54/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
For example, if you have the following component:
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
console.log(testRenderer.toJSON());
// {
// type: 'a',
// props: { href: 'https://www.facebook.com/' },
// children: [ 'Facebook' ]
// }
⬆ Back to Top
⬆ Back to Top
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 55/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
Automatically mocks dependencies when running your tests.
Allows you to test asynchronous code synchronously.
Runs your tests with a fake DOM implementation (via jsdom ) so that your tests can be run on the command line.
Runs tests in parallel processes so that they finish sooner.
⬆ 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
https://github.com/sudheerj/reactjs-interview-questions 56/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
Redux is a predictable state container for JavaScript apps based on the Flux design pattern. Redux can be used together with React, or wit
any other view library. It is tiny (about 2kB) and has no dependencies.
⬆ 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 make
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 jus
pure functions that take the previous state and an action as parameters, and return the next state.
⬆ Back to Top
i. You will need to learn to avoid mutations: Flux is un-opinionated about mutating data, but Redux doesn't like mutations and many
packages complementary to Redux assume you never mutate the state. You can enforce this with dev-only packages like redux-
immutable-state-invariant , Immutable.js, or instructing your team to write non-mutating code.
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.
⬆ Back to Top
mapDispatchToProps() is a utility which will help your component to fire an action event (dispatching action which may cause change of
application state):
It is recommended to always use the “object shorthand” form for the mapDispatchToProps .
Redux wraps it in another function that looks like (…args) => dispatch(onTodoClick(…args)), and pass that wrapper function as a prop to
your component.
const mapDispatchToProps = {
onTodoClick,
};
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 57/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
⬆ Back to Top
store = createStore(myReducer);
⬆ Back to Top
⬆ Back to Top
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
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.
⬆ 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. Yo
can import connect() from react-redux .
https://github.com/sudheerj/reactjs-interview-questions 58/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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 storag
state key.
state = undefined;
}
⬆ Back to Top
The @ symbol is in fact a JavaScript expression used to signify decorators. Decorators make it possible to annotate and modify classes an
properties at design time.
Without decorator:
https://github.com/sudheerj/reactjs-interview-questions 59/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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, an
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 wha
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:
https://github.com/sudheerj/reactjs-interview-questions 60/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
}
});
};
}
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 alway
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.
Container is an informal term for a component that is connected to a Redux store. Containers subscribe to Redux state updates and
dispatch actions, and they usually don't render DOM elements; they delegate rendering to presentational child components.
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 61/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
export const EDIT_TODO = "EDIT_TODO";
export const COMPLETE_TODO = "COMPLETE_TODO";
export const COMPLETE_ALL = "COMPLETE_ALL";
export const CLEAR_COMPLETED = "CLEAR_COMPLETED";
ii. In reducers:
⬆ 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:
https://github.com/sudheerj/reactjs-interview-questions 62/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
The ownProps inside your mapStateToProps() and mapDispatchToProps() functions will be an object:
{
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.fetchUser` function.
// Instructing middleware to call promise, it resolved value will be assigned to `userData` variable
const userData = yield call(api.fetchUser, action.userId);
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 63/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
⬆ Back to Top
⬆ Back to Top
⬆ 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
For example, you can add redux-thunk and logger passing them as arguments to applyMiddleware() :
https://github.com/sudheerj/reactjs-interview-questions 64/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
⬆ 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
https://github.com/sudheerj/reactjs-interview-questions 65/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
$ react-native log-ios
$ react-native log-android
⬆ Back to Top
⬆ 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 th
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
https://github.com/sudheerj/reactjs-interview-questions 66/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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.
https://github.com/sudheerj/reactjs-interview-questions 67/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
⬆ Back to Top
React Angular
React is a library and has only the View layer Angular is a framework and has complete MVC functionality
AngularJS renders only on the client side but Angular 2 and above renders
React handles rendering on the server side
on the server side
React uses JSX that looks like HTML in JS which can be Angular follows the template approach for HTML, which makes code shorter
confusing and easy to understand
In React, data flows only in one way and hence In Angular, data flows both way i.e it has two-way data binding between
debugging is easy children and 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
// 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>
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 68/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
⬆ 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,
https://github.com/sudheerj/reactjs-interview-questions 69/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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
https://github.com/sudheerj/reactjs-interview-questions 70/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
enableReinitialize: true,
})(UserEdit);
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() {
https://github.com/sudheerj/reactjs-interview-questions 71/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
return (
<form onSubmit={this.handleSubmit}>
<input type="text" ref={this.setSearchInput} /> // Access DOM input
in handle submit
<button type="submit">Submit</button>
</form>
);
}
}
⬆ Back to Top
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 th
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
In this approach, the returned HOC class (Enhancer) extends the WrappedComponent. It is called Inheritance Inversion because instead o
the WrappedComponent extending some Enhancer class, it is passively extended by the Enhancer. In this way the relationship between
them seems inverse.
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
https://github.com/sudheerj/reactjs-interview-questions 72/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
219. Do I 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
https://github.com/sudheerj/reactjs-interview-questions 73/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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
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.
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,
https://github.com/sudheerj/reactjs-interview-questions 74/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
}));
};
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 (
<>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</>
);
}
Note: Hooks can be used inside an existing function component without rewriting the component.
⬆ Back to Top
i. Call Hooks only at the top level of your react functions: You shouldn’t call Hooks inside loops, conditions, or nested functions. This
will ensure that Hooks are called in the same order each time a component renders and it preserves the state of Hooks between
multiple useState and useEffect calls.
ii. Call Hooks from React Functions only: You shouldn’t call Hooks from regular JavaScript functions. Instead, you should call them from
either function components or custom hooks.
The eslint plugin named eslint-plugin-react-hooks can be used to enforce these two rules.
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 75/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
For example, the linter enforce proper naming convention for hooks. If you rename your custom hooks which as prefix "use" to somethin
else then linter won't allow you to call built-in hooks such as useState, useEffect etc inside of your custom hook anymore.
⬆ Back to Top
Flux Redux
The Store contains both state and change logic The Store and change logic are separate
There are multiple stores exist There is only one store exist
All the stores are disconnected and flat Single store with hierarchical reducers
React components subscribe to the store Container components uses connect function
⬆ 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
componentDidCatch(error, info);
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 76/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
iii. During Server side rendering
iv. When errors thrown in the error boundary code itself
⬆ 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>
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.
⬆ Back to Top
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 77/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
⬆ 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
⬆ 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
https://github.com/sudheerj/reactjs-interview-questions 78/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
The defaultProps can be defined as a property on the component to set the default values for the props. These default props are used
when props not supplied(i.e., undefined props), but not for null props. That means, If you provide null value then it remains null value.
For example, let us create color default prop for the button component,
function MyButton {
// ...
}
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 the default
value
render() {
return <MyButton /> ; // props.color will contain red value
}
⬆ 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()
https://github.com/sudheerj/reactjs-interview-questions 79/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
iii. render()
iv. getSnapshotBeforeUpdate()
v. componentDidUpdate()
⬆ Back to Top
i. static getDerivedStateFromError()
ii. componentDidCatch()
⬆ Back to Top
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"
);
}
⬆ Back to Top
⬆ Back to Top
ReactDOM.unmountComponentAtNode(container);
⬆ Back to Top
For example, in the below code snippets, it will make moduleA.js and all its unique dependencies as a separate chunk that only loads afte
the user clicks the 'Load' button. moduleA.js
https://github.com/sudheerj/reactjs-interview-questions 80/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
export { moduleA };
App.js
render() {
return (
<div>
<button onClick={this.handleClick}>Load</button>
</div>
);
}
}
⬆ 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 attribute
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 81/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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 />;
}
The above code impacts on 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.
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 DevTool
But If you name the render function then it will appear as ”ForwardRef(myFunction)”
As an alternative, You can also set displayName property for forwardRef function,
function logProps(Component) {
class LogProps extends React.Component {
// ...
}
https://github.com/sudheerj/reactjs-interview-questions 82/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
}
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
https://github.com/sudheerj/reactjs-interview-questions 83/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
i. Throttling: Changes based on a time based frequency. For example, it can be used using _.throttle lodash function
ii. Debouncing: Publish changes after a period of inactivity. For example, it can be used using _.debounce lodash function
iii. RequestAnimationFrame throttling: Changes based on requestAnimationFrame. For example, it can be used using raf-schd lodash
function
⬆ 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 = {
https://github.com/sudheerj/reactjs-interview-questions 84/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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
});
});
}
As mentioned in the above code snippets, this.setState({comments}) updates only comments variable without modifying or replacing
posts variable.
⬆ Back to Top
In the both approaches, the synthetic argument e is passed as a second argument. You need to pass it explicitly for arrow functions and
will be passed automatically for bind method.
⬆ Back to Top
function Greeting(props) {
if (!props.loggedIn) {
return null;
}
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.
https://github.com/sudheerj/reactjs-interview-questions 85/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
⬆ 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 latenc
for large apps.
iii. Redux-Form is 22.5 kB minified gzipped whereas Formik is 12.7 kB
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 86/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
⬆ 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>
);
}
https://github.com/sudheerj/reactjs-interview-questions 87/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
⬆ 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.
https://github.com/sudheerj/reactjs-interview-questions 88/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
return (
<div>
<ThemedButton />
</div>
);
}
// Lets read theme value in the button component to use
class ThemedButton extends React.Component {
static contextType = ThemeContext;
render() {
return <Button theme={this.context} />;
}
}
⬆ Back to Top
⬆ Back to Top
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.
ii. Static field You can use a static class field to initialize your contextType using public class field syntax.
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 89/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
A Consumer is a React component that subscribes to context changes. It requires a function as a child which receives current context valu
as argument and returns a react node. The value argument passed to the function will be equal to the value prop of the closest Provider
for this context above in the tree.
<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.
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;
https://github.com/sudheerj/reactjs-interview-questions 90/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
}
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
⬆ 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 you
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 construct
for event handlers.
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 91/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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:
⬆ 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 bot
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 acros
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.
https://github.com/sudheerj/reactjs-interview-questions 92/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
iv. Recursing On Children: when recursing on the children of a DOM node, React just iterates over both lists of children at the same tim
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,
https://github.com/sudheerj/reactjs-interview-questions 93/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
};
⬆ 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
function withMouse(Component) {
return class extends React.Component {
render() {
return (
<Mouse
render={(mouse) => <Component {...this.props} mouse={mouse} />}
/>
);
}
};
}
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}>
https://github.com/sudheerj/reactjs-interview-questions 94/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
<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
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
https://github.com/sudheerj/reactjs-interview-questions 95/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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>
);
}
We provided an empty array as second argument to the useEffect hook to avoid activating it on component updates. This way, it only
fetches on component mount.
⬆ Back to Top
⬆ Back to Top
i. React DOM
ii. React DOM Server
https://github.com/sudheerj/reactjs-interview-questions 96/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
iii. React Test Renderer
iv. React Shallow Renderer
⬆ Back to Top
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.
⬆ 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
It is a javascript library for managing the application It is a library for reactively managing the state of your
Definition
state applications
Data Store There is only one large store exist for data storage There is more than one store for storage
Usage Mainly used for large and complex applications Used for simple applications
How it stores Uses JS Object to store Uses observable to store the data
⬆ Back to Top
https://github.com/sudheerj/reactjs-interview-questions 98/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
// 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.dispatch} />
// in es6
<SomeComponent {...this.props} />
// es 5
var users = usersList.map(function (user) {
return <li>{user.name}</li>;
});
// es 6
const users = usersList.map((user) => <li>{user.name}</li>);
⬆ 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 t
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
https://github.com/sudheerj/reactjs-interview-questions 99/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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 i
a Hook. In particular, the rule enforces that,
i. Calls to Hooks are either inside a PascalCase function (assumed to be a component) or another useSomething function (assumed to
be a custom Hook).
ii. Hooks are called in the same order on every render.
⬆ Back to Top
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
therefore much simpler to understand.
⬆ Back to Top
⬆ Back to Top
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
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
https://github.com/sudheerj/reactjs-interview-questions 100/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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() {
https://github.com/sudheerj/reactjs-interview-questions 101/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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
⬆ 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 component
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 directly saving in a state variable
}
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:
Now we can use the MessageWrapper component instead of the Message component and the message will be displayed with a border:
Wrapper component can also accept its own props and pass them down to the wrapped component, for example, we can create a wrapp
component that will add a title to the message component:
https://github.com/sudheerj/reactjs-interview-questions 103/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
);
};
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 no
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.
In general, it's recommended to use useEffect as much as possible, because it is more performant and less prone to errors. useLayoutEffe
should only be used when you need to measure or update layout, and you can't achieve the same result using useEffect.
⬆ 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.
Note: The Pascal Case is the recommended approach to provide naming to a component.
Functional component has been improved over the years with some added features like Hooks. Here is a syntax for functional componen
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()
https://github.com/sudheerj/reactjs-interview-questions 104/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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.
The useState() hook can used to implement state in funcitonal component. It returns an array with two items: the first item is current
state and the next one is a function (setState) that updates the value of the current state.
function App() {
const [message, setMessage] = useState("This is a functional component");
const updateMessage = () => {
setMessage("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.
The props are accessible in child class component using this.props as shown in below example,
Props in functional components are similar to that of the class components but the difference is the absence of 'this' keyword.
https://github.com/sudheerj/reactjs-interview-questions 105/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
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
`React.StrictMode` is a useful component for highlighting potential problems in an application. Just like `<Fragment>`,
`<StrictMode>` does not render any extra DOM elements. It activates additional checks and warnings for its descendants. These
checks apply for _development mode_ only.
```jsx harmony
Releases
No releases published
Packages
No packages published
Contributors 94
+ 80 contributors
Languages
https://github.com/sudheerj/reactjs-interview-questions 106/107
2/1/24, 12:09 AM sudheerj/reactjs-interview-questions: List of top 500 ReactJS Interview Questions & Answers....Coding exercise questions are…
https://github.com/sudheerj/reactjs-interview-questions 107/107