ReactJS Interview Questions
ReactJS Interview Questions
Refs are used for managing focus, selecting text and triggering animations.
It also integrates with third-party libraries. Refs help in getting the
reference to a DOM (Document Object Model) node. They return the node
that we are referencing. Whenever we need DOM measurements, we can
use refs.
render() function is used to update the UI. For this, you have to create a
new element and send it to ReactDOM.render(). React elements are
immutable and once you create an element, you cannot change its
attributes. Thus, elements are like a single frame and it depicts the UI at
some point. ReactDOM.render() controls the content of the container node
you pass and if there is any DOM element already present in it then it would
be replaced when first called.
Vue Js- Launched in February 2014, Vue is the most famous and rapidly
growing framework in JS field. Vue is an intuitive, fast and composable
MVVM for building interactive interfaces. It is extremely adaptable and
several JavaScript libraries make use of this. Vue is also a web application
framework that helps in making advanced single page applications.
FLUX REDUX
Flux is a container for application Redux is a container for
state and logic that are registered JavaScript apps.
to callbacks.
It is an observer pattern that is It offers interesting features
modified to fit React. such as writing applications,
testing in different environments
such as a server, client, etc.
It is a fancy name given to In redux, actions can be
observer pattern and Facebook has functions or promises.
developed tools to aid the
implementation of these patterns.
Flux supports actions that are Redux is the first choice for web
simple JavaScript objects. developers because it offers live
code editing.
Class components – most of the tech-savvy people are more familiar with
class components as they have been around the corner for a longer time.
These components make use of plain old javascript objects for creating
pages, mixins, etc in an identical way. Using React’s create a class factory
method, a literal is passed in defining the methods of a new component.
showAlert() {
alert("Im an alert");
}
render() {
return (
<button onClick={this.showAlert}>show alert </button>
);
}
}
10. What is the difference between Dom and virtual Dom in ReactJS ?
DOM is the acronym for Document Object Model. Dom is also called HTML
DOM as it is an abstraction of structured code called HTML for web
developers. Dom and HTML code are interrelated as the elements of HTML
are known as nodes of DOM. It defines a structure where users can create,
alter, modify documents and the content present in it. So while HTML is a
text, DOM is an in-memory representation of this text.
Virtual DOM is an abstraction of abstraction as it has been derived from
HTML DOM. It is a representation of DOM objects like a lightweight copy.
The virtual DOM was not invented by React, it is only used and provided for
free.
React.js is used by web developers for creating large web pages without
reloading the entire page. It uses the data and can be changed over time.
The following are the advantages of using React.js-
4- UI test cases.
Advantages of React Js
React Components let you split the UI into independent, reusable pieces,
and think about each piece in isolation.
Conceptually, components are like JavaScript functions. They accept
arbitrary inputs (called “props”) and return React elements describing what
should appear on the screen.
<li><a href=”#”>Contact Us
</ul> );
Each component has several “lifecycle methods” that you can override to
run code at particular times in the process. Methods prefixed with will are
called right before something happens, and methods prefixed with did are
called right after something happens.
Mounting
constructor()
componentWillMount()
render()
componentDidMount()
Updating
rendered:
componentWillReceiveProps()
shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()
Unmounting
This method is called when a component is being removed from the DOM:
componentWillUnmount()
Other APIs
setState()
forceUpdate()
Class Properties
defaultProps
displayName
Instance Properties
props
state
Source: https://facebook.github.io/react/docs/react-component.html
It’s Adaptability
Free and Open Source
Decorators from ES7
Server-side Communication
Asynchronous Functions & Generators
Flux Library
Destructuring Assignments
Usefulness of JSX
// In HTML
<button onclick="activateAccount()">
Activate Account
</button>
//In React
<button onClick={activateAccount}>
Activate Account
</button>
Another difference is that in React js you cannot return false to prevent
default behavior in React. You must call preventDefault explicitly. Read
more from https://facebook.github.io/react/docs/handling-events.html
Stateless components are components that don’t have any state. When
something is stateless, it calculates its internal state but it never directly
mutates it.For creating a stateless components No class and this keyword is
needed.You can create a stateless components using plain functions or Es6
arrow function. Below is an example of stateless component in react.
//In Es6
const Pane = (props) =>
{props.children}
;
//In Es5
const Username = ({ username }) =>
The logged in user is: {username}
render() {
return (<button
onClick={() => this.updateCount()}
>
Clicked {this.state.count} times
</button>);
}
}
JSX is a syntax extension to JavaScript and comes with the full power of
JavaScript. JSX produces React “elements”. You can embed any JavaScript
expression in JSX by wrapping it in curly braces. After compilation, JSX
expressions become regular JavaScript objects. This means that you can use
JSX inside of if statements and for loops, assign it to variables, accept it as
arguments, and return it from functions. Eventhough React does not require
JSX, it is the recommended way of describing our UI in React app.
For example, below is the syntax for a basic element in React with JSX and
its equivalent without it.
Using an ES6 class to write the same component is a little different. Instead
of using a method from the react library, we extend an ES6 class that the
library defines, Component.
constructor() is a special function in a JavaScript class. JavaScript
invokes constructor() whenever an object is created via a class.
For everything else, there’s React. We use React to define and create our
elements, for lifecycle hooks, etc. i.e. the guts of a React application.
Class components allows us to use additional features such as local state and
lifecycle hooks. Also, to enable our component to have direct access to our
store and thus holds state.
When our component just receives props and renders them to the page, this
is a ‘stateless component’, for which a pure function can be used. These are
also called dumb components or presentational components.
From the previous question, we can say that our Booklist component is
functional components and are stateless.
On the other hand, the BookListContainer component is a class component.
The state is a data structure that starts with a default value when a
Component mounts. It may be mutated across time, mostly as a result of
user events.
Props (short for properties) are a Component’s configuration. Props are how
components talk to each other. They are received from above component
and immutable as far as the Component receiving them is concerned. A
Component cannot change its props, but it is responsible for putting
together the props of its child Components. Props do not have to just be data
— callback functions may be passed in as props.
There is also the case that we can have default props so that props are set
even if a parent component doesn’t pass props down.
Props and State do similar things but are used in different ways. The
majority of our components will probably be stateless. Props are used to
pass data from parent to child or by the component itself. They are
immutable and thus will not be changed. State is used for mutable data, or
data that will change. This is particularly useful for user input.
HOC’s allow you to reuse code, logic and bootstrap abstraction. HOCs are
common in third-party React libraries. The most common is probably
Redux’s connect function. Beyond simply sharing utility libraries and simple
composition, HOCs are the best way to share behavior between React
Components. If you find yourself writing a lot of code in different places that
does the same thing, you may be able to refactor that code into a reusable
HOC.
We don’t need to install or configure tools like Webpack or Babel. They are
preconfigured and hidden so that we can focus on the code. We can install
easily just like any other node modules. Then it is just one command to start
the React project.
A fast interactive unit test runner with built-in support for coverage
reporting.
A build script to bundle JS, CSS, and images for production, with hashes
and sourcemaps.
The basic idea of Redux is that the entire application state is kept in a single
store. The store is simply a javascript object. The only way to change the
state is by firing actions from your application and then writing reducers for
these actions that modify the state. The entire state transition is kept inside
reducers and should not have any side-effects.
Redux is based on the idea that there should be only a single source of truth
for your application state, be it UI state like which tab is active or Data state
like the user profile details.
All of these data is retained by redux in a closure that redux calls a store . It
also provides us a recipe of creating the said store, namely createStore(x).
This store can only be updated by dispatching an action. Our App dispatches
an action, it is passed into reducer; the reducer returns a fresh instance of
the state; the store notifies our App and it can begin it's re render as
required.
When comparing previous props and state to next, a shallow comparison will
check that primitives have the same value (eg, 1 equals 1 or that true equals
true) and that the references are the same between more complex javascript
values like objects and arrays.
It is good to prefer PureComponent over Component whenever we never
mutate our objects.
The virtual DOM is used for efficient re-rendering of the DOM. This isn’t
really related to dirty checking your data. We could re-render using a virtual
DOM with or without dirty checking. In fact, the diff algorithm is a dirty
checker itself.
We aim to re-render the virtual tree only when the state changes. So using
an observable to check if the state has changed is an efficient way to prevent
unnecessary re-renders, which would cause lots of unnecessary tree diffs. If
nothing has changed, we do nothing.
This is because setState alters the state and causes rerendering. This can be
an expensive operation and making it synchronous might leave the browser
unresponsive. Thus the setState calls are asynchronous as well as batched
for better UI experience and performance.
This relates to stateful DOM components (form elements) and the difference:
Action — Actions are payloads of information that send data from our
application to our store. They are the only source of information for the
store. We send them to the store using store.dispatch(). Primarly, they
are just an object describes what happened in our app.
Store — The Store is the object that brings Action and Reducer together.
The store has the following responsibilities: Holds application state;
Allows access to state via getState(); Allows state to be updated
viadispatch(action); Registers listeners via subscribe(listener); Handles
unregistering of listeners via the function returned bysubscribe(listener).
It’s important to note that we’ll only have a single store in a Redux
application. When we want to split your data handling logic, we’ll use
reducer composition instead of many stores.
React.cloneElement clone and return a new React element using using the
passed element as the starting point. The resulting element will have the
original element's props with the new props merged in shallowly. New
children will replace existing children. key and ref from the original element
will be preserved.
React is a JavaScript library, supporting both front end web and being run
on the server, for building user interfaces and web applications.
With React Native it is possible to mimic the behavior of the native app in
JavaScript and at the end, we will get platform specific code as the output.
We may even mix the native code with the JavaScript if we need to optimize
our application further.
Ok, this is more like a warm-up question. Which is even more important to
give a full answer.
An uncontrolled input stores its own state internally, using DOM API.
Here don’t provide value and onChange handler, but we use ref():
<input type="text" ref={this.textInput} />
And now you can access your input data as:
this.textInput.current.value
Your interviewer wants to hear more about details: are there any pros to
using uncontrolled components, is there any performance difference?
Personally, I’ve never used uncontrolled inputs, but if you are learning React
or you have to integrate React and non-React code then it might be
necessary.
It’s nice to mention what your data (state) and UI (inputs) are always in sync
with controlled input approach and it means you have to update the
component’s state which triggers React reconciliation process.
While with uncontrolled elements there is no need for that — you just keep
the value inside the input DOM element.
Q2. Why do we need a key property? Give an example when a bad key causes
an error.
What interviewer wants to see: some insight on how React works internally.
There are classic diffing algorithms with O(n³) time complexity, which might
be used for creating a tree of React elements. But it means for displaying
1000 elements would require one billion comparisons.
What about a bad key? Well, an index might be a very bad key if you decide
to make your children removable. Check out this demo. Try to type
something in the second input and then remove the first one. But you still
can see the value in the second one, why so?
Because your keys are unstable. After removal, your third child with a key
equals to 3, now has a key equals to 2. It’s not the same element for React
now. And it will match it to the wrong DOM element, which previously had a
key equals to 2 (which keeps the value we typed in a second input).
Q3. How React event system is different from DOM events. Using
stopImmediatePropagation().
The best way to answer this question is to first shortly explain how DOM
event concepts like bubbling and capturing work.
In short, with bubbling, the event is first captured and handled by the
innermost element and then propagated to outer elements.
With capturing, the event is first captured by the outermost element and
propagated to the inner elements.
After that would be great to mention that React uses the Event Delegation
Pattern — instead of assigning a handler to each of them — we put a single
handler on their common ancestor and can access that element
with event.target.
What interviewer wants to see: more knowledge about React and you care
about performance.
This is one of the most frequently asked questions. It’s worth to mention:
Check out this deep reading if it’s all vague for you.
What interviewer wants to see: you are familiar with a well-known React
pattern.
We want to create a HOC for making a red border for our Button
component. Let’s create it using our definition:
const withRedBorder = Component =>
(props) => (
<Component {...props} style={{ border: "1px solid red" }} />
);
What interviewer wants to see: you are familiar with a second well-known
React pattern.
An example:
<DataProvider render={data => (
<h1>Hello {data.target}</h1>
)}/>
A follow up: what about HOC vs render props. Which one is better, when to
use? This is a quite controversial topic, in this article you can find some pros
and cons.
React testing library provides a clean and simple API which focuses on
testing applications “as a user would”. This means an API returns HTML
Elements rather than React Components with shallow rendering in Enzyme.
It’s is a nice tool for writing integrational tests.
Enzyme is still a valid tool, it provides a more sophisticated API which gives
you access to component’s props and internal state. It makes sense to
create unit tests for components.
Check out this neat video about react-testing-library.
Despite hooks are still new API, a lot of people already use it in production
and they expect you to know it.
Usage:
const App = () => {
const size = useWindowSize(); return (
<div>
{size.width}px / {size.height}px
</div>
);
}
Yes, but we’ll call useEffect hook on every render which may cause
performance issues.
When you call setSize inside the custom hooks, React knows that this hook is
used in App component and will re-render it.
There is some portion of magic with React hooks. Check out Why Do React
Hooks Rely on Call Order? article for more info.
What interviewer wants to see: arguably the most important thing in React -
how to manage the data flow.
First of all, it’s worth to mention that unlike Redux, the context doesn’t
have its own state, instead, it’s just a conduit and usually reads data from
another component’s state.
Also, with Context API it’s quite easy to re-render much more than you
need even if you use PureComponent or React.memo.
In the example below every time, we click on the button you will see a new
message in the console:
import React, { useState, useContext } from "react";
import ReactDOM from "react-dom";const ProfileContext =
React.createContext();const App = () => {
const [val, setIncrement] = useState(0);
return (
<div>
<Profile userInfo={val} />
<button onClick={() => setIncrement(val + 1)}>Click</button>
<p>value: {val}</p>
</div>
);
};class Profile extends React.PureComponent {
state = {
name: "Alex"
}; setName(name) {
this.setState({ name });
} render() {
const { name } = this.state;
const { setName } = this; return (
<ProfileContext.Provider
value={{
name,
setName
}}
>
<Logger />
</ProfileContext.Provider>
);
}
}const Logger = React.memo(() => {
const { name } = useContext(ProfileContext);
console.log("Logger rerendering");
return null;
});ReactDOM.render(<App />, document.querySelector("#root"));
Now it works as expected. Btw, if you know how to make it work with hooks
— post it in the comment section!
What interviewer wants to see: you have an idea of how to refactor ReactJS
using hooks and you can demonstrate it.
With function components and hooks you can cover all class components
use-cases, such as:
Let’s take a look at the example below and refactor it using hooks:
class App extends React.Component {
state = {
value: localStorage.getItem("info") || ""
}; componentDidUpdate() {
localStorage.setItem("info", this.state.value);
} onChange = event => {
this.setState({ value: event.target.value });
}; render() {
const { value } = this.state;
return (
<div>
<input value={value} type="text" onChange={this.onChange} />
<p>{value}</p>
</div>
);
}
}
This is already quite compact, thanks to class fields declaration and class
arrow functions.
Only 13 lines of code instead of 19 with classes with exactly the same
functionality. But we can go one step further: we can easily extract and
reuse a custom hook here:
const usePersistentStorage = key => {
const val = localStorage.getItem(key) || "";
const [value, setValue] = useState(val); useEffect(() =>
localStorage.setItem(key, value), [key, value]); return [value, setValue];
};