react interview questions Flashcards
What is React?
It is an open-source front-end JavaScript library most popular for single-page web applications. It is helpful when interactive and complex UIs are built for websites or mobile apps. React.js was released for use in 2015 and since then it has become one of the most trusted and used technologies of recent time. It has built one of the largest developer communities around itself.
List some of React.js’ features.
The major features of React are:
- 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.
how React’s virtual DOM prevents wasteful DOM manipulation
The Problem
DOM manipulation is the heart of the modern, interactive web. Unfortunately, it is also a lot slower than most JavaScript operations.
This slowness is made worse by the fact that most JavaScript frameworks update the DOM much more than they have to.
As an example, let’s say that you have a list that contains ten items. You check off the first item. Most JavaScript frameworks would rebuild the entire list. That’s ten times more work than necessary! Only one item changed, but the remaining nine get rebuilt exactly how they were before.
Rebuilding a list is no big deal to a web browser, but modern websites can use huge amounts of DOM manipulation. Inefficient updating has become a serious problem.
To address this problem, the people at React popularized something called the virtual DOM.
The Virtual DOM
Here is a refresher of what happens behind the scenes in The Virtual DOM.
In React, for every DOM object, there is a corresponding “virtual DOM object.” A virtual DOM object is a representation of a DOM object, like a lightweight copy.
A virtual DOM object has the same properties as a real DOM object, but it lacks the real thing’s power to directly change what’s on the screen.
Manipulating the DOM is slow. Manipulating the virtual DOM is much faster because nothing gets drawn onscreen. Think of manipulating the virtual DOM as editing a blueprint, as opposed to moving rooms in an actual house.
How It Helps
When you render a JSX element, every single virtual DOM object gets updated.
This sounds incredibly inefficient, but the cost is insignificant because the virtual DOM can update so quickly.
Once the virtual DOM has been updated, then React compares the virtual DOM with a virtual DOM snapshot that was taken right before the update.
By comparing the new virtual DOM with a pre-update version, React figures out exactly which virtual DOM objects have changed. This process is called “diffing.”
Once React knows which virtual DOM objects have changed, then React updates those objects, and only those objects, on the real DOM. In our example from earlier, React would be smart enough to rebuild your one checked-off list-item and leave the rest of your list alone.
This makes a big difference! React can update only the necessary parts of the DOM. React’s reputation for performance comes largely from this innovation.
In summary, here’s what happens when you try to update the DOM in React:
- The entire virtual DOM gets updated.
- The virtual DOM gets compared to what it looked like before you updated it. React figures out which objects have changed.
- The changed objects, and the changed objects only, get updated on the real DOM.
- Changes on the real DOM cause the screen to change.
what is virtual DOM in react?
In React, for every DOM object, there is a corresponding “virtual DOM object.” A virtual DOM object is a representation of a DOM object, like a lightweight copy.
A virtual DOM object has the same properties as a real DOM object, but it lacks the real thing’s power to directly change what’s on the screen.
Manipulating the DOM is slow. Manipulating the virtual DOM is much faster because nothing gets drawn onscreen. Think of manipulating the virtual DOM as editing a blueprint, as opposed to moving rooms in an actual house.
source
What Is Server Side Rendering?
Server Side Rendering (SSR) is used to render web pages on the server before sending them to the client. This allows for faster page loads, improved performance, and an SEO-friendly rendering solution for React applications. In addition, SSR can provide a better experience for users with slower internet connections or devices with limited memory and processing power by performing the initial rendering of components on the server.
SSR in React can improve page load times by eliminating unnecessary roundtrips between client and server. Server Side Rendering in React provides more control over how content appears within search engine results pages (SERPs). Since search engine crawlers rely heavily on JavaScript while indexing websites, websites built entirely with Client-Side Rendering may not appear correctly within SERPs due to their inability to parse JavaScript code.
Server Side Rendering, compared to Client-Side Rendering is that it helps ensure consistency across different browsers; since much of modern web development relies heavily upon browser specific features like APIs or custom event handlers – these types of features may not always behave properly when rendered through Client-Side techniques alone but will function normally if prerendered via Server Side methods beforehand.
source
What is unidirectional data flow in React?
Unidirectional data flow describes a one-way data flow where the data can move in only one pathway when being transferred between different parts of the program.
React, a Javascript library, uses unidirectional data flow. The data from the parent is known as props. You can only transfer data from parent to child and not vice versa.
This means that the child components cannot update or modify the data on their own, making sure that a clean data flow architecture is followed. This also means that you can control the data flow better.
source
Advantages of unidirectional data flow in react?
Effect of state changes
In React, each state is owned by one component. Due to the unidirectional flow, the changes made on the state of the component will only affect the children and not the parents or siblings.
Advantages of unidirectional data flow
There are many advantages of unidirectional data flow, some of which are listed below:
Debugging
One-way data flow makes debugging much easier. When the developer knows where the data is coming from and where it is going, they can dry run (or use tools) to find the problems more efficiently.
Better control
Having data flow in one direction makes the program less prone to errors and gives the developer more control.
Efficiency
As the used libraries are wary of the limitations and specifications of the unidirectional flow, extra resources are not wasted, leading to an efficient process.
source
What are the main advantages of React.js?
The main advantages of React.js are:
- It enhances the performance of the application
- It can be used from the client-side as well as the server-side
- The readability of code is higher in React.js because of JSX
- It offers easy integration with frameworks such as Angular, Meteor, etc.
- It is easy to write UI test cases with React.js
If you can include some practical experience demonstrating the advantages of React.js in this React.js interview question, you are likely to impress the recruiter.
what is JSX in react?
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.
export default function App() { return ( <h1 className="greeting">{"Hello, this is a JSX Code!"}</h1> ); }
If you don’t use JSX syntax then the respective JavaScript code should be written as below,
import { createElement } from 'react'; export default function App() { return createElement( 'h1', { className: 'greeting' }, 'Hello, this is a JSX Code!' ); }
Describe an event in React.js?
When a user presses a key, clicks the mouse, or performs any action on the machine or when the machine itself triggers an action, these actions are registered as events in React.js.
In React.js, we use camelCase to name events, instead of the lowercase in HTML
In React.js, because of JSX, a function is passed as an event handler, instead of the string in HTML
For example, in traditional HTML, you might have something like this:
html
<button onclick="handleClick()">Click me</button>
In React.js with JSX, you would write something like this:
<button onClick={handleClick}>Click me</button>
Here, handleClick is a reference to a function defined elsewhere in your code that you want to be executed when the button is clicked. This approach is more inline with JavaScript conventions and allows for more flexibility and maintainability in React applications.
How do Lists work in React.js?
Lists in React.js are created similar to how they are created in regular Javascript. With lists, data can be displayed in an orderly manner and is useful in displaying menus on websites. For traversing lists, the map() function is used. For example,
An array of numbers is taken by the map() function and their value is multiplied by 5
var numbers = [2,4,6,8,10]
const multiplyNums = numbers.map((number => {
return (number*5);
});
console.log (multiplyNums);
Output: The output in Javascript will be logged in the console. The output in the above case is [10, 20, 30, 40, 50]
Why are keys used in React.js Lists?
Keys are used in React.js lists for two primary reasons:
- Efficient Reconciliation: React uses keys to efficiently update the UI when the underlying data changes. When rendering a list of elements, React needs a way to uniquely identify each element in the list. Keys provide a way for React to identify which items have changed, been added, or been removed. This helps React perform a process called reconciliation, where it updates the DOM only for the elements that have changed, rather than re-rendering the entire list.
- Optimizing Rendering Performance: Keys help optimize rendering performance by allowing React to determine which components can be re-used, moved, or removed efficiently. When a list is re-rendered, React compares the keys of the new elements with the keys of the old elements to identify the minimal set of changes needed to update the UI. Without keys, React would have to resort to less efficient methods to track changes in the list.
In summary, keys are essential in React.js lists to enable efficient updates and optimize rendering performance by uniquely identifying list elements and aiding the reconciliation process.
Is HTML used in React?
No, it uses an HTML-in JavaScript syntax called JSX (JavaScript and XML) that converts HTML tags to React elements.
Can you tell two downsides of React?
Steep Learning Curve for Beginners: React introduces a paradigm shift for many developers, especially those coming from a primarily imperative or jQuery background. JSX, component-based architecture, and concepts like state management and props can be challenging to grasp initially. This steep learning curve can slow down the onboarding process for new developers and require significant investment in learning.
Boilerplate Code: While React itself is relatively lightweight, building complex applications often requires integrating with other libraries and tools for state management (such as Redux), routing, form handling, and more. This can lead to a significant amount of boilerplate code, especially for larger applications. Managing this boilerplate code and keeping it organized can add complexity to the project and increase development time and maintenance overhead.
It’s important to note that while these downsides exist, they can often be mitigated with experience, good architectural decisions, and the use of additional tools and libraries within the React ecosystem.
Can you outline the differences between Real DOM and Virtual DOM?
What is Flux?
Flux is a word made up to describe one-way (unidirectional) data flow with very specific events and listeners. There’s no official Flux library, but it’s a pattern we can use react and many works.
there are a lot of components used in Flux. Let’s go through all the components one by one.
View: this component renders the UI. Whenever any user interaction occurs on it (like an event) then it fires off the action. Also when the Store informs the View that some change has occurred, it re-renders itself. For example, if a user clicks the Add button.
Action: this handles all the events. These events are passed by the view component. This layer is generally used to make API calls. Once the action is done it is dispatched using the Dispatcher. The action can be something like add a post, delete a post, or any other user interaction.
The common structure of the payload for dispatching an event is as follows:
{
actionType: “”,
data: {
title: “Understanding Flux step by step”,
author: “Sharvin”
}
}
The actionType key is compulsory and it is used by the dispatcher to pass updates to the related store. It is also a known practice to use constants to hold the value name for actionType key so no typos occur. Data holds the event information that we want to dispatch from Action to Store. The name for this key can be anything.
Dispatcher: this is the central hub and singleton registry. It dispatches the payload from Actions to Store. Also makes sure that there are no cascading effects when an action is dispatched to the store. It ensures that no other action happens before the data layer has completed processing and storing operations.
Consider this component has a traffic controller in the system. It is a centralized list of callbacks. It invokes the callback and broadcasts the payload it received from the action.
Due to this component, the data flow is predictable. Every action updates the specific store with the callback that is registered with the dispatcher.
Store: this holds the app state and is a data layer of this pattern. Do not consider it as a model from MVC. An application can have one or many app stores. Stores get updated because they have a callback that is registered using the dispatcher.
Node’s event emitter is used to update the store and broadcast the update to view. The view never directly updates the application state. It is updated because of the changes to the store.
This is only part of Flux that can update the data. Interfaces implemented in the store are as follows:
- The EventEmitter is extended to inform the view that store data has been updated.
- Listeners like addChangeListener and removeChangeListener are added.
- emitChange is used to emit the change.
what is observer pattern?
Observer is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing.
source
what is redux?
Redux is a pattern and library for managing and updating application state, using events called “actions”. It serves as a centralized store for state that needs to be used across your entire application, with rules ensuring that the state can only be updated in a predictable fashion.
source
Why Should I Use Redux?
Redux helps you manage “global” state - state that is needed across many parts of your application.
The patterns and tools provided by Redux make it easier to understand when, where, why, and how the state in your application is being updated, and how your application logic will behave when those changes occur. Redux guides you towards writing code that is predictable and testable, which helps give you confidence that your application will work as expected.
source
When Should I Use Redux?
Redux helps you deal with shared state management, but like any tool, it has tradeoffs. There are more concepts to learn, and more code to write. It also adds some indirection to your code, and asks you to follow certain restrictions. It’s a trade-off between short term and long term productivity.
Redux is more useful when:
- You have large amounts of application state that are needed in many places in the app
- The app state is updated frequently over time
- The logic to update that state may be complex
- The app has a medium or large-sized codebase, and might be worked on by many people
how to update an object or an array immutabily in js?
In order to update values immutably, your code must make copies of existing objects/arrays, and then modify the copies.
Is this true or false:
Redux expects that all state updates are done immutably?
true
what is an action in redux?
An action is a plain JavaScript object that has a type field. You can think of an action as an event that describes something that happened in the application.
The type field should be a string that gives this action a descriptive name, like “todos/todoAdded”. We usually write that type string like “domain/eventName”, where the first part is the feature or category that this action belongs to, and the second part is the specific thing that happened.
An action object can have other fields with additional information about what happened. By convention, we put that information in a field called payload.
A typical action object might look like this:
const addTodoAction = {
type: ‘todos/todoAdded’,
payload: ‘Buy milk’
}
source
what are action creators in redux?
An action creator is a function that creates and returns an action object. We typically use these so we don’t have to write the action object by hand every time:
const addTodo = text => {
return {
type: ‘todos/todoAdded’,
payload: text
}
}
{`Hello, ${message}`}
; } ``` **Class Components**: You can also use ES6 class to define a component. The above function component can be written as a class component: ``` class Greeting extends React.Component { render() { return{`Hello, ${this.props.message}`}
; } } ```Hello!
; { messages.length > 0 && !isLogin ? (You have {messages.length} unread messages.
) : (You don't have unread messages.
); } ```This is the parent component
{children}This is passed as a child to the ParentComponent
and
{title}
{description}
{date}
{story.title}
{story.description}
{story.date}
{title}
{description}
{date}
> ); } ```Hello, world!
{`Welcome, ${name}`}
{`Age, ${age}`}
> ); } User.propTypes = { name: PropTypes.string.isRequired, age: PropTypes.number.isRequired, }; ```Hello, world!
Value: {value}
Value: {value}
{name}
{address &&{address}
}{name}
{address ?{address}
:{"Address is not available"}
}` tag so that the formatting of the JSON.stringify() is retained: ``` const data = { name: "John", age: 42 }; class User extends React.Component { render() { return{JSON.stringify(data, null, 2)}; } } React.render(, document.getElementById("container")); ```
-
{employees.map((employee) => (
- {employee.name}-{employee.experience} ))}
{`Hello ${data.target}`}
} /> ``` Libraries such as React Router and DownShift are using this pattern.{someData}
{someValue}
which is centered, red and sized at 1.5em
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
// Create a component that renders a 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.
```
{"Lets start first styled component!"}
```
- Brad
- Brodge
- Brandon
{prop1}
{prop2}
{name}
; ``` This way you can prevent XSS(Cross-site-scripting) attacks in the application.-
{data.hits.map((item) => (
- {item.title} ))}