React I Flashcards

1
Q

What are the major features of React?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is JSX?

A

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.

Note: JSX is stricter than HTML

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the difference between Element and Component?

A

An Element is a plain object describing what you want to appear on the screen in terms of the DOM nodes or other components. Elements can contain other Elements in their props. Creating a React element is cheap. Once an element is created, it cannot be mutated.

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.

Then JSX gets transpiled to a React.createElement() function tree.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to create components in React?

A

Components are the building blocks of creating User Interfaces(UI) in React. There are two possible ways to create a component.

Function Components: This is the simplest way to create a component. Those are pure JavaScript functions that accept props object as the one and only one parameter and return React elements to render the output:

function Greeting({ message }) {
  return <h1>{`Hello, ${message}`}</h1>;
}

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 <h1>{Hello, ${this.props.message}}</h1>;
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

When to use a Class Component over a Function Component?

A

After the addition of Hooks(i.e. React 16.8 onwards) it is always recommended to use Function components over Class components in React. Because you could use state, lifecycle methods and other features that were only available in class component present in function component too.

But even there are two reasons to use Class components over Function components.

If you need a React functionality whose Function component equivalent is not present yet, like Error Boundaries.
In older versions, If the component needs state or lifecycle methods then you need to use class component.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Use Function Components:

A

If you don’t need state or lifecycle methods, and your component is purely presentational.
For simplicity, readability, and modern code practices, especially with the use of React Hooks for state and side effects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Use Class Components:

A

If you need to manage state or use lifecycle methods.
In scenarios where backward compatibility or integration with older code is necessary.

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are Pure Components?

A

Pure components are the components which render the same output for the same state and props. In function components, you can achieve these pure components through memoized React.memo() API wrapping around the component. This API prevents unnecessary re-renders by comparing the previous props and new props using shallow comparison. So it will be helpful for performance optimizations.

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.

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.

Note: React.memo() is a higher-order component.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is state in React?

A

State of a component is an object that holds some information that may change over the lifetime of the component. The important point is whenever the state object changes, the component re-renders. It is always recommended to make our state as simple as possible and minimize the number of stateful components.

Let’s take an example of User component with message state. Here, useState hook has been used to add state to the User component and it returns an array with current state and function to update it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are props in React?

A

Props are inputs to components. They are single values or objects containing a set of values that are passed to components on creation similar to HTML-tag attributes. Here, the data is passed down from a parent component to a child component.

The primary purpose of props in React is to provide following component functionality:

Pass custom data to your component.
Trigger state changes.
Use via this.props.reactProp inside component's render() method.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the difference between state and props?

A

In React, both state and props are plain JavaScript objects and used to manage the data of a component, but they are used in different ways and have different characteristics.

The state entity is managed by the component itself and can be updated using the setter(setState() for class components) function. Unlike props, state can be modified by the component and is used to manage the internal state of the component. i.e, state acts as a component’s memory. Moreover, changes in the state trigger a re-render of the component and its children. The components cannot become reusable with the usage of state alone.

On the otherhand, props (short for “properties”) are passed to a component by its parent component and are read-only, meaning that they cannot be modified by the own component itself. i.e, props acts as arguments for a function. Also, props can be used to configure the behavior of a component and to pass data between components. The components become reusable with the usage of props.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the difference between HTML and React event handling?

A

Below are some of the main differences between HTML and React event handling,

In HTML, the event name usually represents in lowercase as a convention:

<button onclick="activateLasers()"></button>

Whereas in React it follows camelCase convention:

<button onClick={activateLasers}>

In HTML, you can return false to prevent default behavior:

<a></a>

Whereas in React you must call preventDefault() explicitly:

function handleClick(event) {
event.preventDefault();
console.log(“The link was clicked.”);
}

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are synthetic events in React?

A

SyntheticEvent is a cross-browser wrapper around the browser’s native event. Its API is same as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers. The native events can be accessed directly from synthetic events using nativeEvent attribute.

function BookStore() {
function handleTitleChange(e) {
console.log(“The new title is:”, e.target.value);
// ‘e’ represents synthetic event
const nativeEvent = e.nativeEvent;
console.log(nativeEvent);
e.stopPropagation();
e.preventDefault();
}

return <input name=”title” onChange={handleTitleChange} />;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are inline conditional expressions?

A

You can use either if statements or** ternary expressions** which are available from JS to conditionally render expressions. Apart from these approaches, you can also embed any expressions in JSX by wrapping them in curly braces and then followed by JS logical operator &&.

<h1>Hello!</h1>

;
{
messages.length > 0 && !isLogin ? (
<h2>You have {messages.length} unread messages.</h2>
) : (
<h2>You don’t have unread messages.</h2>
);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is “key” prop and what is the benefit of using it in arrays of elements?

A

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:

const todoItems = todos.map((todo) => <li key={todo.id}>{todo.text}</li>);

When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort:

const todoItems = todos.map((todo, index) => (
<li key={index}>{todo.text}</li>
));

Note:
Using indexes for keys is not recommended if the order of items may change. This can negatively impact performance and may cause issues with component state.

If you extract list item as separate component then apply keys on list component instead of li tag.

There will be a warning message in the console if the key prop is not present on list items.

The key attribute accepts either string or number and internally convert it as string type.

Don't generate the key on the fly something like key={Math.random()}. Because the keys will never match up between re-renders and DOM created everytime.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is Virtual DOM?

A

The Virtual DOM (VDOM) is an in-memory representation of Real DOM.

The representation of a UI is** kept in memory** and synced with the “realDOM. It’s a step that happens between the render function being called and the displaying of elements on the screen. This entire process is called reconciliation.

The Virtual DOM works in three simple steps.

** Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representati**on.

Then the difference between the previous DOM representation and the new one is calculated.

Once the calculations are done, the real DOM will be updated with only the things that have actually changed.

17
Q

What is the difference between Shadow DOM and Virtual DOM?

A

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.

18
Q

What is React Fiber?

A

Fiber is the new reconciliation engine or reimplementation of core algorithm in React v16. The goal of React Fiber is to increase its suitability for areas like animation, layout, gestures, ability to pause, abort, or reuse work and assign priority to different types of updates; and new concurrency primitives.

Reconciliation is the process React uses to efficiently update the DOM when the state or props of a component change. Instead of re-rendering everything, React compares the new virtual DOM with the previous one and updates only the changed parts.

19
Q

What is the main goal of React Fiber?

A

The goal of React Fiber is to increase its suitability for areas like animation, layout, and gestures. Its headline feature is incremental rendering: the ability to split rendering work into chunks and spread it out over multiple frames.

from documentation

Its main goals are:

Ability to split interruptible work in chunks.
Ability to prioritize, rebase and reuse work in progress.
Ability to yield back and forth between parents and children to support layout in React.
Ability to return multiple elements from render().
Better support for error boundaries.
20
Q

What are controlled components?

A

A component that controls the input elements within the forms on subsequent user input is called Controlled Component, i.e, every state mutation will have an associated handler function. That means, the displayed data is always in sync with the state of the component.

The controlled components will be implemented using the below steps,

Initialize the state using useState hooks in function components or inside constructor for class components.
	
Set the value of the form element to the respective state variable.
	
Create an event handler to handle the user input changes through useState updater function or setState from class component.
	
Attach the above event handler to form elements change or click events
21
Q

What are uncontrolled components?

A

The Uncontrolled Components are the ones that store their own state internally, and you query the DOM using a ref to find its current value when you need it. This is a bit more like traditional HTML.

The uncontrolled components will be implemented using the below steps,

Create a ref using useRef react hook in function component or React.createRef() in class based component.
Attach this ref to the form element.
The form element value can be accessed directly through ref in event handlers or componentDidMount for class components
22
Q

What is the difference between createElement and cloneElement?

A

JSX elements will be transpiled to React.createElement() functions to create React elements which are going to be used for the object representation of UI. Whereas cloneElement is used to clone an element and pass it new props.

23
Q

What is Lifting State Up in React?

A

When several components need to share the same changing data then it is recommended to lift the shared state up to their closest common ancestor. That means if two child components share the same data from its parent, then move the state to parent instead of maintaining local state in both of the child components.

24
Q

What are Higher-Order Components?

A

A higher-order component (HOC) is a function that takes a component and returns a new component.

Basically, it’s a pattern that is derived from React’s compositional nature.

We call them pure components because they can accept any dynamically provided child component but they won’t modify or copy any behavior from their input components.

const EnhancedComponent = higherOrderComponent(WrappedComponent);

HOC can be used for many use cases:

Code reuse, logic and bootstrap abstraction.
Render hijacking.
State abstraction and manipulation.
Props manipulation.
25
Q

What is children prop?

A

Children is a prop that allows you to pass components as data to other components, just like any other prop you use. Component tree put between component’s opening and closing tag will be passed to that component as children prop.

A simple usage of children prop looks as below,

function MyDiv({ children }){
return (
<div>
{children}
</div>;
);
}

export default function Greeting() {
return (
<MyDiv>
<span>{"Hello"}</span>
<span>{"World"}</span>
</MyDiv>
);
}

26
Q

How to write comments in React?

A

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>

27
Q

What is reconciliation?

A

Reconciliation is the process through which React updates the Browser DOM and makes React work faster. React use a diffing algorithm so that component updates are predictable and faster. React would first calculate the difference between the real DOM and the copy of DOM (Virtual DOM) when there’s an update of components. React stores a copy of Browser DOM which is called Virtual DOM. When we make changes or add data, React creates a new Virtual DOM and compares it with the previous one. This comparison is done by Diffing Algorithm. Now React compares the Virtual DOM with Real DOM. It finds out the changed nodes and updates only the changed nodes in Real DOM leaving the rest nodes as it is. This process is called Reconciliation.

28
Q

Does the lazy function support named exports?

A

No, currently React.lazy function supports default exports only. If you would like to import modules which are named exports, you can create an intermediate module that reexports it as the default. It also ensures that tree shaking keeps working and don’t pull unused components. Let’s take a component file which exports multiple named components,

// MoreComponents.js
export const SomeComponent = /* … /;
export const UnusedComponent = /
… */;

and reexport MoreComponents.js components in an intermediate file IntermediateComponent.js

// IntermediateComponent.js
export { SomeComponent as default } from “./MoreComponents.js”;

Now you can import the module using lazy function as below,

import React, { lazy } from “react”;
const SomeComponent = lazy(() => import(“./IntermediateComponent.js”));

29
Q

Why React uses className over class attribute?

A

The attribute names written in JSX turned into keys of JavaScript objects and the JavaScript names cannot contain dashes or reserved words, it is recommended to use camelCase wherever applicable in JSX code. The attribute class is a keyword in JavaScript, and JSX is an extension of JavaScript. That’s the principle reason why React uses className instead of class. Pass a string as the className prop.

render() {
return <span>{‘Menu’}</span>
}

30
Q

What are fragments?

A

It’s a common pattern or practice in React for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM. You need to use either <Fragment> or a shorter syntax having empty tag (<></>).</Fragment>

Below is the example of how to use fragment inside Story component.

function Story({ title, description, date }) {
return (
<Fragment>
<h2>{title}</h2>
<p>{description}</p>
<p>{date}</p>
</Fragment>
);
}

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>
));
}

31
Q

Why fragments are better than container divs?

A

Below are the list of reasons to prefer fragments over container DOM elements,

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.
Some CSS mechanisms like Flexbox and CSS Grid have a special parent-child relationships, and adding divs in the middle makes it hard to keep the desired layout.
The DOM Inspector is less cluttered.
32
Q

What are portals in React?

A

Portal is a recommended way to render children into a DOM node that exists outside the DOM hierarchy of the parent component. When using CSS transform in a component, its descendant elements should not use fixed positioning, otherwise the layout will blow up.

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.

33
Q

What are stateless components?

A

If the behaviour of a component is independent of its state then it can be a stateless component. You can use either a function or a class for creating stateless components. But unless you need to use a lifecycle hook in your components, you should go for function components. There are a lot of benefits if you decide to use function components here; they are easy to write, understand, and test, a little faster, and you can avoid the this keyword altogether.

34
Q

What are stateful components?

A

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,

import React, {useState} from ‘react’;

const App = (props) => {
const [count, setCount] = useState(0);
handleIncrement() {
setCount(count+1);
}

return (
<>
<button onClick={handleIncrement}>Increment</button>
<span>Counter: {count}</span>
</>
)
}

35
Q

How to apply validation on props in React?

A

When the application is running in development mode, React will automatically check all props that we set on components to make sure they have correct type. If the type is incorrect, React will generate warning messages in the console. It’s disabled in production mode due to performance impact. The mandatory props are defined with isRequired.

The set of predefined prop types:

PropTypes.number
PropTypes.string
PropTypes.array
PropTypes.object
PropTypes.func
PropTypes.node
PropTypes.element
PropTypes.bool
PropTypes.symbol
PropTypes.any
36
Q

What are the advantages of React?

A

Below are the list of main advantages of React,

Increases the application's performance with Virtual DOM.
JSX makes code easy to read and write.
It renders both on client and server side (SSR).
Easy to integrate with frameworks (Angular, Backbone) since it is only a view library.
Easy to write unit and integration tests with tools such as Jest.
37
Q

What are the limitations of React?

A

Apart from the advantages, there are few limitations of React too,

React is just a view library, not a full framework.
There is a learning curve for beginners who are new to web development.
Integrating React into a traditional MVC framework requires some additional configuration.
The code complexity increases with inline templating and JSX.
Too many smaller components leading to over engineering or boilerplate.