react interview questions Flashcards

1
Q

What is React?

A

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.

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

List some of React.js’ features.

A

The major features of React are:

  1. Uses JSX syntax, a syntax extension of JS that allows developers to write HTML in their JS code.
  2. It uses Virtual DOM instead of Real DOM considering that Real DOM manipulations are expensive.
  3. Supports server-side rendering which is useful for Search Engine Optimizations(SEO).
  4. 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
3
Q

how React’s virtual DOM prevents wasteful DOM manipulation

A

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:

  1. The entire virtual DOM gets updated.
  2. The virtual DOM gets compared to what it looked like before you updated it. React figures out which objects have changed.
  3. The changed objects, and the changed objects only, get updated on the real DOM.
  4. Changes on the real DOM cause the screen to change.

source

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

what is virtual DOM in react?

A

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

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

What Is Server Side Rendering?

A

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

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

What is unidirectional data flow in React?

A

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

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

Advantages of unidirectional data flow in react?

A

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

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

What are the main advantages of React.js?

A

The main advantages of React.js are:

  1. It enhances the performance of the application
  2. It can be used from the client-side as well as the server-side
  3. The readability of code is higher in React.js because of JSX
  4. It offers easy integration with frameworks such as Angular, Meteor, etc.
  5. 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

what is JSX in react?

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.

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!'
  );
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Describe an event in React.js?

A

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

How do Lists work in React.js?

A

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]

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

Why are keys used in React.js Lists?

A

Keys are used in React.js lists for two primary reasons:

  1. 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.
  2. 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.

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

Is HTML used in React?

A

No, it uses an HTML-in JavaScript syntax called JSX (JavaScript and XML) that converts HTML tags to React elements.

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

Can you tell two downsides of React?

A

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.

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

Can you outline the differences between Real DOM and Virtual DOM?

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

What is Flux?

A

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:

  1. The EventEmitter is extended to inform the view that store data has been updated.
  2. Listeners like addChangeListener and removeChangeListener are added.
  3. emitChange is used to emit the change.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

what is observer pattern?

A

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

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

what is redux?

A

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

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

Why Should I Use Redux?

A

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

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

When Should I Use Redux?

A

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:

  1. You have large amounts of application state that are needed in many places in the app
  2. The app state is updated frequently over time
  3. The logic to update that state may be complex
  4. The app has a medium or large-sized codebase, and might be worked on by many people
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

how to update an object or an array immutabily in js?

A

In order to update values immutably, your code must make copies of existing objects/arrays, and then modify the copies.

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

Is this true or false:
Redux expects that all state updates are done immutably?

A

true

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

what is an action in redux?

A

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

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

what are action creators in redux?

A

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

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

what is a reducer in redux?

A

A reducer is a function that receives the current state and an action object, decides how to update the state if necessary, and returns the new state: (state, action) => newState. You can think of a reducer as an event listener which handles events based on the received action (event) type.
source

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

what are the rules that a reducer must always follow?

A

Reducers must always follow some specific rules:

  1. They should only calculate the new state value based on the state and action arguments
  2. They are not allowed to modify the existing state. Instead, they must make immutable updates, by copying the existing state and making changes to the copied values.
  3. They must not do any asynchronous logic, calculate random values, or cause other “side effects”

The logic inside reducer functions typically follows the same series of steps:

  1. Check to see if the reducer cares about this action
  2. If so, make a copy of the state, update the copy with new values, and return it
  3. Otherwise, return the existing state unchanged

Here’s a small example of a reducer, showing the steps that each reducer should follow:

const initialState = { value: 0 }

function counterReducer(state = initialState, action) {
  // Check to see if the reducer cares about this action
  if (action.type === 'counter/increment') {
    // If so, make a copy of `state`
    return {
      ...state,
      // and update the copy with the new value
      value: state.value + 1
    }
  }
  // otherwise return the existing state unchanged
  return state
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

why reducers are called reducers in redux?

A

The Array.reduce() method lets you take an array of values, process each item in the array one at a time, and return a single final result. You can think of it as “reducing the array down to one value”.

Array.reduce() takes a callback function as an argument, which will be called one time for each item in the array. It takes two arguments:

previousResult, the value that your callback returned last time
currentItem, the current item in the array
The first time that the callback runs, there isn’t a previousResult available, so we need to also pass in an initial value that will be used as the first previousResult.

If we wanted to add together an array of numbers to find out what the total is, we could write a reduce callback that looks like this:

const numbers = [2, 5, 8]

const addNumbers = (previousResult, currentItem) => {
  console.log({ previousResult, currentItem })
  return previousResult + currentItem
}

const initialValue = 0

const total = numbers.reduce(addNumbers, initialValue)
// {previousResult: 0, currentItem: 2}
// {previousResult: 2, currentItem: 5}
// {previousResult: 7, currentItem: 8}

console.log(total)
// 15

Notice that this addNumbers “reduce callback” function doesn’t need to keep track of anything itself. It takes the previousResult and currentItem arguments, does something with them, and returns a new result value.

A Redux reducer function is exactly the same idea as this “reduce callback” function! It takes a “previous result” (the state), and the “current item” (the action object), decides a new state value based on those arguments, and returns that new state.

If we were to create an array of Redux actions, call reduce(), and pass in a reducer function, we’d get a final result the same way:

const actions = [
  { type: 'counter/increment' },
  { type: 'counter/increment' },
  { type: 'counter/increment' }
]

const initialState = { value: 0 }

const finalResult = actions.reduce(counterReducer, initialState)
console.log(finalResult)
// {value: 3}

We can say that Redux reducers reduce a set of actions (over time) into a single state. The difference is that with Array.reduce() it happens all at once, and with Redux, it happens over the lifetime of your running app.

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

what is store in redux?

A

The current Redux application state lives in an object called the store.

The store is created by passing in a reducer, and has a method called getState that returns the current state value:

import { configureStore } from '@reduxjs/toolkit'

const store = configureStore({ reducer: counterReducer })

console.log(store.getState())
// {value: 0}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

what is dispatch function in redux?

A

The Redux store has a method called dispatch. The only way to update the state is to call store.dispatch() and pass in an action object. The store will run its reducer function and save the new state value inside, and we can call getState() to retrieve the updated value:

store.dispatch({ type: 'counter/increment' })

console.log(store.getState())
// {value: 1}

You can think of dispatching actions as “triggering an event” in the application. Something happened, and we want the store to know about it. Reducers act like event listeners, and when they hear an action they are interested in, they update the state in response.

We typically call action creators to dispatch the right action:

const increment = () => {
  return {
    type: 'counter/increment'
  }
}

store.dispatch(increment())

console.log(store.getState())
// {value: 2}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

what are selectors in redux?

A

Selectors are functions that know how to extract specific pieces of information from a store state value. As an application grows bigger, this can help avoid repeating logic as different parts of the app need to read the same data:

const selectCounterValue = state => state.value

const currentValue = selectCounterValue(store.getState())
console.log(currentValue)
// 2
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What is a high order component in React?

A

In React, a higher-order component is a function that takes a component as an argument and returns a new component that wraps the original component.

HOCs allow you to add additional functionality to a component without modifying the component’s code. For example, you can use a HOC to add authentication or routing capabilities to a component or to apply a specific style or behavior to multiple components.

HOCs can take additional arguments, which lets you customize the behavior of the HOC. This makes them a flexible and reusable way to add functionality to your components.
source

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

Benefits of Using Higher-Order Components in React?

A
  1. Reusability: HOCs allow you to reuse component logic across multiple components, which can save time and reduce code duplication.
  2. Flexibility: HOCs can take additional arguments, which allows you to customize the behavior of the HOC. This makes them a flexible way to add functionality to your components.
  3. Separation of concerns: HOCs can help separate concerns in your code by encapsulating certain functionality in a separate component. This can make the code easier to read and maintain.
  4. Composition: HOCs can be composed together to create more complex functionality. This allows you to build up functionality from smaller, reusable pieces.
  5. Higher-order components can be used to implement cross-cutting concerns in your application such as authentication, error handling, logging, performance tracking, and many other features.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What is the Presentational segment in react?

A

Container/Presentational Pattern
In React, one way to enforce separation of concerns is by using the Container/Presentational pattern. With this pattern, we can separate the view from the application logic.

Let’s say we want to create an application that fetches 6 dog images, and renders these images on the screen.

Ideally, we want to enforce separation of concerns by separating this process into two parts:
1. Presentational Components: Components that care about how data is shown to the user. In this example, that’s the rendering the list of dog images.
2. Container Components: Components that care about what data is shown to the user. In this example, that’s fetching the dog images.

source

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

Explain Props in ReactJS.

A

Props in React mean properties. They act as a communication channel from parent to child.

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

What does super keyword mean in React?

A

It is used to call super or parent class

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

List the two types of React component.

A

Two types of React component are as follows:

  1. Function component
  2. Class component
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What are synthetic events in ReactJS ?

A

Synthetic events in React are cross-browser wrappers around the browser’s original event. Different browsers may have different names for the events. They create a uniform interface that React uses to ensure that events execute consistently across browsers. React normalizes this information to provide a consistent API for handling events regardless of the browser.

e.preventDefault()       // prevents all the default behavior by the browser.
e.stopPropagation()   // prevents the call to the parent component whenever a child component gets called.

Note: Here ‘e’ is a synthetic event, a cross-browser object. It is made with a wrapper around the actual event of the browser.

Some of the attributes are:
1. bubbles: Return true or false indicates event is a bubbling event or not.
2. cancelable: Return true or false indicates if the event can be canceled or not.
3. currentTarget: Indicates the element to which the handler is attached
4. defaultPrevented: Return true or false, indicates whether the event has been canceled by preventDefault().
5. eventPhase: Returns number, indicates the phase
6. isTrusted: Return true when the event is generated by the user and false when by the browser/script
7. type: Returns string, it indicates the type of the event

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

What are three main phases of react component lifecycle?

A

A component’s lifecycle has three main phases: the Mounting Phase, the Updating Phase, and the Unmounting Phase.

The Mounting Phase begins when a component is first created and inserted into the DOM. The Updating Phase occurs when a component’s state or props change. And the Unmounting Phase occurs when a component is removed from the DOM.

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

what is component mounting phase?

A

The mounting phase refers to the period when a component is being created and inserted into the DOM.

During this phase, several lifecycle methods are invoked by React to enable the developer to configure the component, set up any necessary state or event listeners, and perform other initialization tasks.

The mounting phase has three main lifecycle methods that are called in order:
1. constructor()
2. render()
3. getDerivedStateFromProps()

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

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

what is jest?

A

Jest is a well-liked testing tool that makes it simple to test JavaScript applications, particularly those created using JavaScript-based frameworks like React. It is an open-source technology that has won the trust of many developers and is supported by the tech giant Facebook.

Why use Jest to test React Apps?

  1. Zero Configuration: Jest does not require an extensive configuration before you’re all set to start to test React applications. This is one of Jest’s most useful features, which makes it any developer’s first pick.
  2. Snapshot Testing: While developers make every effort to implement changes exactly as a designer intended, snapshot testing helps ensure this occurs. The visual representation of a code is recorded and then compared with a screenshot of a new scenario to validate whether there is a difference.
  3. React Integration: Jest is also mentioned in the official React documentation, emphasizing that it interacts easily with React development. It also works nicely with tools like the React Testing Library, which was created for user-centric testing of React components.
  4. Community Support: Since Jest is widely utilized in the React development community, there are a ton of resources available to help with any problems one may run into when using Jest to test React applications. The developers benefit from the abundance of instructions and solutions that are available online in numerous forums.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

what is callback function?

A

A JavaScript callback is a function which is to be executed after another function has finished execution. A more formal definition would be - Any function that is passed as an argument to another function so that it can be executed in that other function is called as a callback function.

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

Explain React State.

A

It is an object which stores the component’s property values. Also, it decides how the component renders and behaves.

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

what are arrow functions in js?

A

Arrow function {()=>} is concise way of writing JavaScript functions in shorter way. Arrow functions were introduced in the ES6 version. They make our code more structured and readable. Arrow functions are anonymous functions i.e. functions without a name but they are often assigned to any variable

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

how many ways a state can be updated in react?

A

it can be updated directly or indirectly. To implement this one can use either this. setState function or the reducer function.

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

what problem does react context solves?

A

context api solves the problem of prop drilling.
Prop drilling basically means that in order to pass props from parent to lowest child, we have to make it pass through all the intermediate components also. It means that on every state update, all the intermediary components will be forced to re-render, which badly affects the performance of the application.

for eg- in the below given, image to show the updated user info in the profile screen, new state will be passed down right from app component to the lowest profile component.

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

what is react context?

A

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

For example, authenticated users, locale preferences, UI themes need to be accessed in the application by many components.

const { Provider, Consumer } = React.createContext(defaultValue);

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

how to decide which tool to use: redux or context api in react?

A

Does React Context replace Redux? The short answer is no, it doesn’t. As we’ve seen, Context and Redux are two different tools, and comparison often arises from misconceptions about what each tool is designed for. Although Context can be orchestrated to act as a state management tool, it wasn’t designed for that purpose, so you’d have to do put in extra effort to make it work. There are already many state management tools that work well and will ease your troubles.

In my experience with Redux, it can be relatively complex to achieve something that is easier to solve today with Context. Keep in mind, prop drilling and global state management is where Redux and Context’s paths cross. Redux has more functionality in this area. Ultimately, Redux and Context should be considered complementary tools that work together instead of as alternatives. My recommendation is to use Redux for complex global state management and Context for prop drilling.

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

what is webpack?

A

Webpack in react is a JavaScript module bundler that is commonly used with React to bundle and manage dependencies. It takes all of the individual JavaScript files and other assets in a project, such as images and CSS, and combines them into a single bundle that can be loaded by the browser. Webpack also has the ability to transpile modern JavaScript code (such as ES6) into older versions that can be understood by older browsers.

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

what is babel?

A

Babel is a JavaScript compiler
Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. Here are the main things Babel can do for you:

  1. Transform syntax
  2. Polyfill features that are missing in your target environment (through a third-party polyfill such as core-js)
  3. Source code transformations (codemods)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

How are ReactJS and React Native different?

A

Where ReactJS is a front end open-source JavaScript library for UIs, React Native is an open-source mobile framework for platforms such as Android and iOS.

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

How do browsers read JSX files?

A

React, a JavaScript library for web applications utilizes JSX—a syntax extension allowing JavaScript objects within HTML elements, enhancing code clarity. JSX isn’t directly supported by browsers, requiring conversion by tools like Babel to transform JSX into valid JavaScript. This transpilation ensures browsers can interpret and execute the JSX-embedded code in React applications.
source

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

Mention one difference between Props and State.

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. 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 component 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.

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

The JavaScript representation(Without JSX) of React Element would be as follows:

const element = React.createElement("div", { id: "login-btn" }, "Login");

and this element can be simiplified using JSX

  <div id="login-btn">Login</div>
The above React.createElement() function returns an object as below:

{
  type: 'div',
  props: {
    children: 'Login',
    id: 'login-btn'
  }
}

Finally, this element renders to the DOM using ReactDOM.render().

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:

const Button = ({ handleLogin }) => (
  <div id={"login-btn"} onClick={handleLogin}>
    Login
  </div>
);

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

const Button = ({ handleLogin }) =>
  React.createElement(
    "div",
    { id: "login-btn", onClick: handleLogin },
    "Login"
  );
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
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 first 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
56
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.

  1. If you need a React functionality whose Function component equivalent is not present yet, like Error Boundaries.
  2. 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";

import { ErrorBoundary } from "react-error-boundary";

<ErrorBoundary fallback={<div>Something went wrong</div>}>
  <ExampleApplication />
</ErrorBoundary>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
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.

read further

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

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.

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

  1. Pass custom data to your component.
  2. Trigger state changes.
  3. 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
60
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. 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 component 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.

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

Why should we not update the state directly?

A

If you try to update the state directly then it won’t re-render the component.

//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.

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

What is the purpose of callback function as an argument of setState()?

A

The callback function is invoked when setState finished and the component gets rendered. Since setState() is asynchronous the callback function is used for any post action.

Note: It is recommended to use lifecycle method rather than this callback function.

setState({ name: "John" }, () =>
  console.log("The name has updated and component re-rendered")
);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
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
  href="#"
  onclick='console.log("The link was clicked."); return false;'
/>

Whereas in React you must call preventDefault() explicitly:

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

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
64
Q

t

How to pass a parameter to an event handler or callback?

A

You can use an arrow function to wrap around an event handler and pass parameters:

<button onClick={() => this.handleClick(id)} />

This is an equivalent to calling .bind:

<button onClick={this.handleClick.bind(this, id)} />

Apart from these two approaches, you can also pass arguments to a function which is defined as arrow function

<button onClick={this.handleClick(id)} />;
handleClick = (id) => () => {
  console.log("Hello, your ticket number is", id);
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
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.

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

  return <input name="title" onChange={handleTitleChange} />
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
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
67
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:
1. 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.
2. If you extract list item as separate component then apply keys on list component instead of li tag.
3. There will be a warning message in the console if the key prop is not present on list items.
4. The key attribute accepts either string or number and internally convert it as string type.

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

What is the use of refs?

A

The ref is used to return a reference to the element. They should be avoided in most cases, however, they can be useful when you need a direct access to the DOM element or an instance of a component.

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

what are react refs?

A

Refs in React are short for references. As the name suggests, they allow you to reference and interact with DOM nodes or React components directly. Refs come in handy when you need to reference some information in a component, but you don’t want that information to trigger new renders.

Common use cases of React refs include:

  1. Managing focus, text selection, or media playback
  2. Triggering imperative animations
  3. Integrating with third-party DOM libraries
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q

how to create refs in react?

A

In React, Refs can be created by using either the createRef method or the useRef Hook.

Creating Refs using the useRef Hook
You can create refs using the useRef Hook, which is available as part of the React library. Here’s an example of creating a reference in a functional component:

import React, { useRef } from "react";

function ActionButton() {
  const buttonRef = useRef(null);

  function handleClick() {
    console.log(buttonRef.current);
  }

  return (
    <button onClick={handleClick} ref={buttonRef}>
      Click me
    </button>
  );
};
export default ActionButton;

In the code snippet above, we used the useRef() Hook to create a reference to the button element, which we named buttonRef. This reference enables us to access the current value of buttonRef using buttonRef.current. One advantage of using a ref is that it maintains its state across renders, making it a valuable tool for storing and updating values without causing unnecessary re-renders.

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

What are forward refs?

A

Ref forwarding is a feature that lets some components take a ref they receive, and pass it further down to a child.

const ButtonElement = React.forwardRef((props, ref) => (
  <button ref={ref} className="CustomButton">
    {props.children}
  </button>
));

// Create ref to the DOM button:
const ref = React.createRef();
<ButtonElement ref={ref}>{"Forward Ref"}</ButtonElement>;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q

How Virtual DOM works?

A

The Virtual DOM works in three simple steps.

  1. Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representation.
  2. Then the difference between the previous DOM representation and the new one is calculated.
  3. Once the calculations are done, the real DOM will be updated with only the things that have actually changed.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
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.

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

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

  1. Ability to split interruptible work in chunks.
  2. Ability to prioritize, rebase and reuse work in progress.
  3. Ability to yield back and forth between parents and children to support layout in React.
  4. Ability to return multiple elements from render().
  5. Better support for error boundaries.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
76
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.

For example, to write all the names in uppercase letters, we use handleChange as below,

handleChange(event) {
  this.setState({value: event.target.value.toUpperCase()})
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
77
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.

In the below UserProfile component, the name input is accessed using ref.

class UserProfile extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.input = React.createRef();
  }

  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.

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

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

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

What are the different phases of component lifecycle after react 16.3 ? Diagram question

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

What are the different phases of component lifecycle before react 16.3 ? Diagram question

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

what does componentWillMount function do?

A

componentWillMount: Executed before rendering and is used for App level configuration in your root component.

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

what does componentDidMount do?

A

componentDidMount: Executed after first rendering and here all AJAX requests, DOM or state updates, and set up event listeners should occur.

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

what does componentWillReceiveProps do?

A

componentWillReceiveProps: Executed when particular prop updates to trigger state transitions.

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

what does shouldComponentUpdate function do?

A

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.

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

what does componentWillUpdate do?

A

componentWillUpdate: Executed before re-rendering the component when there are props & state changes confirmed by shouldComponentUpdate() which returns true.

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

what does componentDidUpdate do?

A

componentDidUpdate: Mostly it is used to update the DOM in response to prop or state changes. This will not fire if shouldComponentUpdate() returns false.

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

what does componentWillUnmount do?

A

componentWillUnmount: It will be used to cancel any outgoing network requests, or remove all event listeners associated with the component.

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

what does getDerivedStateFromProps do?

A

getDerivedStateFromProps: Invoked right before calling render() and is invoked on every render. This exists for rare use cases where you need a derived state. Worth reading if you need derived state.

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

what does getSnapshotBeforeUpdate do?

A

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.

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

what does componentWillUnmount do?

A

componentWillUnmount It will be used to cancel any outgoing network requests, or remove all event listeners associated with the component.

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

  1. Code reuse, logic and bootstrap abstraction.
  2. Render hijacking.
  3. State abstraction and manipulation.
  4. Props manipulation.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
93
Q

How to create props proxy for HOC component?

A

You can add/edit props passed to the component using props proxy pattern like this:

function HOC(WrappedComponent) {
  return class Test extends Component {
    render() {
      const newProps = {
        title: "New Header",
        footer: false,
        showFeatureX: false,
        showFeatureY: true,
      };

      return <WrappedComponent {...this.props} {...newProps} />;
    }
  };
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
94
Q

What is children prop?

A

In React, the children prop is a special prop that allows components to pass elements or components as children to other components. This enables the creation of composite components, where one component can encapsulate and render other components or elements within it.

Here’s a basic example to illustrate its usage:

// ParentComponent.js
import React from 'react';

const ParentComponent = ({ children }) => {
  return (
    <div className="parent">
      <h1>This is the parent component</h1>
      {children}
    </div>
  );
};

export default ParentComponent;

In this example, the ParentComponent accepts a children prop and renders it within its own JSX structure.

You can use this ParentComponent in another component like this:

// AnotherComponent.js
import React from 'react';
import ParentComponent from './ParentComponent';

const AnotherComponent = () => {
  return (
    <ParentComponent>
      <p>This is passed as a child to the ParentComponent</p>
      <button>Click me</button>
    </ParentComponent>
  );
};

export default AnotherComponent;

In this example, the <p> and <button> elements, along with any other elements or components passed within the <ParentComponent> tags, become the children of the ParentComponent. They will be rendered inside the ParentComponent wherever the {children} placeholder is located within its JSX.</ParentComponent></button>

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

What is the purpose of using super constructor with props argument?

A

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:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    console.log(this.props); // prints { name: 'John', age: 42 }
  }
}

Not passing props:

class MyComponent extends React.Component {
  constructor(props) {
    super();

    console.log(this.props); // prints undefined

    // but props parameter is still available
    console.log(props); // prints { name: 'John', age: 42 }
  }

  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.

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

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

How to set state with a dynamic key name?

A

If you are using ES6 or the Babel transpiler to transform your JSX code then you can accomplish this with computed property names.

handleInputChange(event) {
this.setState({ [event.target.id]: event.target.value })
}

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

What would be the common mistake of function being called every time the component renders?

A

You need to make sure that function is not being called while passing the function as a parameter.

render() {
  // Wrong: handleClick is called instead of passed as a reference!
  return <button onClick={this.handleClick()}>{'Click Me'}</button>
}

Instead, pass the function itself without parenthesis:

render() {
  // Correct: handleClick is passed as a reference!
  return <button onClick={this.handleClick}>{'Click Me'}</button>
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
100
Q

what is lazy function in react?

A

In React, the lazy function is used for code splitting and lazy loading components. This allows you to load components asynchronously, meaning they are only loaded when they are needed, rather than all at once when the application initializes. Lazy loading is especially useful for large applications where loading all components upfront may lead to longer initial load times.

Here’s how you can use the lazy function:

const MyLazyComponent = React.lazy(() => import('./MyComponent'));

In this example, MyComponent is imported dynamically using the import() function, which returns a Promise. React.lazy takes a function that calls import() and returns a promise for a module containing a React component. When the component is needed, React will then load the component’s module and render it.

You can then use MyLazyComponent as you would any other component:

const App = () => (
  <div>
    <Suspense fallback={<div>Loading...</div>}>
      <MyLazyComponent />
    </Suspense>
  </div>
);

In the above code, <Suspense> is used to wrap the lazy-loaded component. It allows you to specify a fallback UI to display while the lazy component is loading. Once the lazy-loaded component is loaded, it will be rendered in place of the fallback UI.</Suspense>

It’s important to note that lazy loading should be used judiciously, as it adds complexity to the application and can affect user experience if not implemented carefully. It’s typically most beneficial for larger applications where reducing initial load times is a priority.

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

Is lazy function supports 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"));
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
102
Q

Why React uses className over class attribute?

A

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 className={'menu navigation-menu'}>{'Menu'}</span>
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
103
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 or a shorter syntax having empty tag (<></>).

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

Usually, you don’t need to use until unless there is a need of key attribute. The usage of shorter syntax looks like below.

function Story({title, description, date}) {
  return (
      <>
        <h2>{title}</h2>
        <p>{description}</p>
        <p>{date}</p>
      </>
    );
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
104
Q

Why fragments are better than container divs?

A

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

  1. 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.
  2. 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.
  3. The DOM Inspector is less cluttered.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
105
Q

What are portals in React?

A

In React, portals provide a way to render children components into a DOM node that exists outside of the parent component’s DOM hierarchy. This means you can render components into a different part of the DOM tree, allowing for more flexible and powerful UI layouts.

Portals are useful for scenarios like modals, tooltips, or any other UI element that needs to visually “break out” of its parent container but still be managed by React.

Here’s a basic example of how you can use portals in React:

import React from 'react';
import ReactDOM from 'react-dom';

// Define a modal component
const Modal = ({ children }) => {
  return ReactDOM.createPortal(
    children,
    document.getElementById('modal-root')
  );
};

// App component using the Modal
const App = () => (
  <div>
    <h1>Hello, world!</h1>
    <Modal>
      <div>
        This is a modal content.
        <button>Close</button>
      </div>
    </Modal>
  </div>
);

// Render the App component
ReactDOM.render(<App />, document.getElementById('root'));

In this example:

  1. We define a Modal component that accepts children.
    Inside the Modal component, we use ReactDOM.createPortal() to render the children into a separate DOM node with the id modal-root. This node can be located anywhere in the HTML structure, not necessarily a child of the Modal component.
  2. In the App component, we render the Modal component along with other content. The content inside the Modal will be rendered into the modal-root DOM node.

This way, even though the Modal component is declared inside the App component, it’s rendered outside of its DOM hierarchy, allowing for overlays or pop-ups without being constrained by the parent’s styles or layout.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
106
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>
  </>
  )
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
107
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

import React from "react";
import PropTypes from "prop-types";

function User({ name, age }) {
  return (
    <>
      <h1>{`Welcome, ${name}`}</h1>
      <h2>{`Age, ${age}`}</h2>
    </>
  );
}

User.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number.isRequired,
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
108
Q

What are the limitations of React?

A
  1. React is just a view library, not a full framework.
  2. There is a learning curve for beginners who are new to web development.
  3. Integrating React into a traditional MVC framework requires some additional configuration.
  4. The code complexity increases with inline templating and JSX.
  5. Too many smaller components leading to over engineering or boilerplate.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
109
Q

What are error boundaries in React v16?

A

In React, an error boundary is a React component that catches JavaScript errors anywhere in its child component tree, logs those errors, and displays a fallback UI instead of crashing the whole application. This helps in gracefully handling errors and prevents the entire UI from crashing due to a single component’s error.

Here’s an example of how you can create and use an error boundary with functional components:

import React, { useState } from 'react';

// Error boundary component
const ErrorBoundary = ({ children }) => {
  const [hasError, setHasError] = useState(false);

  // Error handling logic
  const componentDidCatch = (error, info) => {
    console.error('Error caught by error boundary:', error, info);
    setHasError(true);
  };

  // Fallback UI
  if (hasError) {
    return <div>Something went wrong. Please try again later.</div>;
  }

  // Render children if no error
  return children;
};

// Error-prone child component
const ChildComponent = () => {
  const handleClick = () => {
    throw new Error('An error occurred in ChildComponent!');
  };

  return (
    <div>
      <button onClick={handleClick}>Click to throw error</button>
    </div>
  );
};

// App component
const App = () => (
  <div>
    <h1>Hello, world!</h1>
    <ErrorBoundary>
      <ChildComponent />
    </ErrorBoundary>
  </div>
);

export default App;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
110
Q

How are error boundaries handled in React v15?

A

React v15 provided very basic support for error boundaries using unstable_handleError method. It has been renamed to componentDidCatch in React v16.

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

What are the recommended ways for static type checking?

A

Normally we use PropTypes library (React.PropTypes moved to a prop-types package since React v15.5) for type checking in the React applications. For large code bases, it is recommended to use static type checkers such as Flow or TypeScript, that perform type checking at compile time and provide auto-completion features.

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

What is the use of react-dom package?

A

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:

  1. render()
  2. hydrate()
  3. unmountComponentAtNode()
  4. findDOMNode()
  5. createPortal()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
113
Q

What is the purpose of render method of react-dom?

A

This method is used to render a React element into the DOM in the supplied container and return a reference to the component. If the React element was previously rendered into container, it will perform an update on it and only mutate the DOM as necessary to reflect the latest changes.

ReactDOM.render(element, container, [callback])
If the optional callback is provided, it will be executed after the component is rendered or updated.

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

What is ReactDOMServer?

A

The ReactDOMServer object enables you to render components to static markup (typically used on node server). This object is mainly used for server-side rendering (SSR). The following methods can be used in both the server and browser environments:

renderToString()
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";

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

How to use innerHTML in React?

A

The dangerouslySetInnerHTML attribute is React’s replacement for using innerHTML in the browser DOM. Just like innerHTML, it is risky to use this attribute considering cross-site scripting (XSS) attacks. You just need to pass a __html object as key and HTML text as value.

In this example MyComponent uses dangerouslySetInnerHTML attribute for setting HTML markup:

function createMarkup() {
  return { \_\_html: "First &middot; Second" };
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}
116
Q

How to use styles in React?

A

The style attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM style JavaScript property, is more efficient, and prevents XSS security holes.

const divStyle = {
  color: "blue",
  backgroundImage: "url(" + imgUrl + ")",
};

function HelloWorldComponent() {
  return <div style={divStyle}>Hello World!</div>;
}

Style keys are camelCased in order to be consistent with accessing the properties on DOM nodes in JavaScript (e.g. node.style.backgroundImage).

117
Q

How events are different in React?

A

Handling events in React elements has some syntactic differences:

  1. React event handlers are named using camelCase, rather than lowercase.
  2. With JSX you pass a function as the event handler, rather than a string.
118
Q

What will happen if you use setState() in constructor?

A

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.

119
Q

What is the impact of indexes as keys?

A

Keys should be stable, predictable, and unique so that React can keep track of elements.

In the below code snippet each element’s key will be based on ordering, rather than tied to the data that is being represented. This limits the optimizations that React can do.

{
  todos.map((todo, index) => <Todo {...todo} key={index} />);
}

If you use element data for unique key, assuming todo.id is unique to this list and stable, React would be able to reorder elements without needing to reevaluate them as much.

{
  todos.map((todo) => <Todo {...todo} key={todo.id} />);
}
120
Q

Is it good to use setState() in componentWillMount() method?

A

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]
      })
    })
}
121
Q

What will happen if you use props in initial state?

A

Using props in the initial state of a React component can lead to unexpected behavior because the initial state is only set once when the component is first created, and it doesn’t automatically update if the props change later. This can lead to inconsistencies between the state and the actual props, especially if the props are expected to change over time.

Here’s an example to illustrate the issue:

import React, { useState } from 'react';

const MyComponent = ({ initialValue }) => {
  // Using props in initial state
  const [value, setValue] = useState(initialValue);

  const handleChange = () => {
    // Update state based on the initial prop
    setValue(initialValue + 1);
  };

  return (
    <div>
      <p>Value: {value}</p>
      <button onClick={handleChange}>Increment Value</button>
    </div>
  );
};

export default MyComponent;

In this example, the initial state of value is set to the initialValue prop passed to the component. However, if the initialValue prop changes after the component has been rendered, the state value won’t update accordingly because it’s only set once during the initial render.

To address this issue, you should use props directly within the component and manage state based on props changes using the useEffect hook.

Here’s how you can do it:

import React, { useState, useEffect } from 'react';

const MyComponent = ({ initialValue }) => {
  // Use state to manage the value
  const [value, setValue] = useState(initialValue);

  // Update state when initialValue prop changes
  useEffect(() => {
    setValue(initialValue);
  }, [initialValue]);

  const handleChange = () => {
    // Update state based on the current value
    setValue(prevValue => prevValue + 1);
  };

  return (
    <div>
      <p>Value: {value}</p>
      <button onClick={handleChange}>Increment Value</button>
    </div>
  );
};

export default MyComponent;

In this revised example, we use the useEffect hook to update the state value whenever the initialValue prop changes. This ensures that the state stays synchronized with the props. Additionally, we use the functional form of setValue to correctly update the state based on the previous state value.

122
Q

How do you conditionally render components?

A

In some cases you want to render different components depending on some state. JSX does not render false or undefined, so you can use conditional short-circuiting to render a given part of your component only if a certain condition is true.

const MyComponent = ({ name, address }) => (
  <div>
    <h2>{name}</h2>
    {address && <p>{address}</p>}
  </div>
);

If you need an if-else condition then use ternary operator.

const MyComponent = ({ name, address }) => (
  <div>
    <h2>{name}</h2>
    {address ? <p>{address}</p> : <p>{"Address is not available"}</p>}
  </div>
);
123
Q

Why we need to be careful when spreading props on DOM elements?

A

When we spread props using the {…} syntax onto a DOM element, we risk adding unknown HTML attributes. This can be problematic because unknown attributes might not behave as expected or could even lead to rendering errors. It’s generally considered a bad practice to add unknown attributes to DOM elements.

Instead of spreading all props onto the DOM element directly, the recommendation is to destructure the props using the {…rest} operator. This way, only the explicitly defined props are passed down to the DOM element, avoiding the inclusion of any unknown attributes.

In the given example:

const ComponentA = () => (
  <ComponentB isDisplay={true} className={"componentStyle"} />
);

const ComponentB = ({ isDisplay, ...domProps }) => (
  <div {...domProps}>{"ComponentB"}</div>
);

ComponentA renders ComponentB with two props: isDisplay and className. Inside ComponentB, isDisplay is extracted explicitly, and the rest of the props (if any) are collected into domProps using the destructuring syntax {…domProps}. Then, domProps are spread onto the div element. This ensures that only the isDisplay prop is specifically handled within ComponentB, and any additional props are safely applied to the div without risking the inclusion of unknown HTML attributes.

124
Q

How you use decorators in React?

A

In React, decorators are a way to enhance or modify the behavior of classes or components. They are functions that wrap around components to add additional functionality. Decorators are typically used with class components, although they can also be used with functional components via libraries like @babel/plugin-proposal-decorators.

Decorators can be used for various purposes, such as adding state management (like Redux’s connect), applying styling (like CSS-in-JS libraries such as styled-components), or adding authentication logic, among others.

Here’s an example of a decorator:

function Logger(Component) {
  return class extends React.Component {
    componentDidMount() {
      console.log('Component was mounted');
    }

    render() {
      return <Component {...this.props} />;
    }
  };
}

@Logger
class MyComponent extends React.Component {
  render() {
    return <div>Hello, World!</div>;
  }
}

In this example, the Logger function is a decorator that logs a message when the component it wraps (MyComponent) is mounted.

125
Q

what is memo in react?

A

In React, memo is a higher-order component (HOC) that is used to optimize the performance of functional components by preventing unnecessary re-renders. It’s similar to the React.PureComponent class for class components.

When a component is wrapped with React.memo(), React will only re-render the component if its props have changed. If the props remain the same between renders, React will reuse the previously rendered result, improving performance by avoiding unnecessary rendering and reconciliation.

Here’s an example of how memo is used:

import React from 'react';

const MyComponent = React.memo((props) => {
  // Component logic here
});

export default MyComponent;
In this example, MyComponent is a functional component that has been wrapped with React.memo(). Now, whenever MyComponent is rendered, React will automatically memoize the result and only re-render it if its props have changed.

It’s important to note that memo only performs a shallow comparison of props. If the props passed to the component contain complex data structures (such as objects or arrays), changes within those data structures may not be detected, and the component may not re-render when it should. In such cases, you may need to implement custom logic within your component to ensure proper rendering when using memo.

Overall, memo is a powerful tool for optimizing the performance of React functional components by reducing unnecessary re-renders. It’s particularly useful for optimizing components that receive static or infrequently changing props.

126
Q

How you implement Server Side Rendering or SSR?

A

React is already equipped to handle rendering on Node servers. A special version of the DOM renderer is available, which follows the same pattern as on the client side.

import ReactDOMServer from "react-dom/server";
import App from "./App";

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.

127
Q

How to enable production mode in React?

A

You should use Webpack’s DefinePlugin method to set NODE_ENV to production, by which it strip out things like propType validation and extra warnings. Apart from this, if you minify the code, for example, Uglify’s dead-code elimination to strip out development only code and comments, it will drastically reduce the size of your bundle.

128
Q

What is CRA and its benefits?

A

The create-react-app CLI tool allows you to quickly create & run React applications with no configuration step.

It includes everything we need to build a React app:

  1. React, JSX, ES6, and Flow syntax support.
  2. Language extras beyond ES6 like the object spread operator.
  3. Autoprefixed CSS, so you don’t need -webkit- or other prefixes.
  4. A fast interactive unit test runner with built-in support for coverage reporting.
  5. A live development server that warns about common mistakes.
  6. A build script to bundle JS, CSS, and images for production, with hashes and sourcemaps.
129
Q

What is the lifecycle methods order in mounting?

A

The lifecycle methods are called in the following order when an instance of a component is being created and inserted into the DOM.

  1. constructor()
  2. static getDerivedStateFromProps()
  3. render()
  4. componentDidMount()
130
Q

What are the lifecycle methods going to be deprecated in React v16?

A

The following lifecycle methods going to be unsafe coding practices and will be more problematic with async rendering.

componentWillMount()
componentWillReceiveProps()
componentWillUpdate()
Starting with React v16.3 these methods are aliased with UNSAFE_ prefix, and the unprefixed version will be removed in React v17.

131
Q

What is the purpose of getDerivedStateFromProps() lifecycle method?

A

The new static getDerivedStateFromProps() lifecycle method is invoked after a component is instantiated as well as before it is re-rendered. It can return an object to update state, or null to indicate that the new props do not require any state updates.

class MyComponent extends React.Component {
  static getDerivedStateFromProps(props, state) {
    // ...
  }
}

This lifecycle method along with componentDidUpdate() covers all the use cases of componentWillReceiveProps().

132
Q

What is the purpose of getSnapshotBeforeUpdate() lifecycle method?

A

The new getSnapshotBeforeUpdate() lifecycle method is called right before DOM updates. The return value from this method will be passed as the third parameter to componentDidUpdate().

class MyComponent extends React.Component {
  getSnapshotBeforeUpdate(prevProps, prevState) {
    // ...
  }
}

This lifecycle method along with componentDidUpdate() covers all the use cases of componentWillUpdate().

133
Q

Do Hooks replace render props and higher order components?

A

Hooks do not directly replace render props and higher-order components (HOCs), but they offer an alternative approach to achieving similar goals in a more concise and readable manner.

Render Props:
Render props is a pattern where a component accepts a function as a prop, which it calls to render its content. This pattern is often used for sharing code between components, particularly for cross-cutting concerns like state management, data fetching, or event handling.

Hooks provide an alternative to render props by allowing you to encapsulate and share stateful logic within a function, eliminating the need for passing callback functions as props. Components can directly use hooks to access and manage state, simplifying the code and making it more readable.

Higher-Order Components (HOCs):
HOCs are functions that accept a component as input and return a new component with enhanced functionality. They are commonly used for code reuse, cross-cutting concerns, and adding additional props or behavior to components.

While hooks don’t replace HOCs directly, they offer a more elegant and composable solution for sharing logic between components. Instead of wrapping components with HOCs, you can extract shared logic into custom hooks and reuse them across multiple components. This approach eliminates the need for nested components and improves code readability.

In summary, while hooks don’t replace render props and HOCs one-to-one, they offer a modern alternative for achieving similar goals in a more straightforward and readable way. They promote a more functional programming style and encourage code reuse and composition, leading to cleaner and more maintainable React codebases.

134
Q

What is the recommended ordering of methods in component class?

A

Recommended ordering of methods from mounting to render stage:

static methods
constructor()
getChildContext()
componentWillMount()
componentDidMount()
componentWillReceiveProps()
shouldComponentUpdate()
componentWillUpdate()
componentDidUpdate()
componentWillUnmount()
click handlers or event handlers like onClickSubmit() or onChangeDescription()
getter methods for render like getSelectReason() or getFooterContent()
optional render methods like renderNavigation() or renderProfilePicture()
render()

135
Q

What is a switching component?

A

A switching component is a component that renders one of many components. We need to use object to map prop values to components.

For example, a switching component to display different pages based on page prop:

import HomePage from "./HomePage";
import AboutPage from "./AboutPage";
import ServicesPage from "./ServicesPage";
import ContactPage from "./ContactPage";

const PAGES = {
  home: HomePage,
  about: AboutPage,
  services: ServicesPage,
  contact: ContactPage,
};

const Page = (props) => {
  const Handler = PAGES[props.page] || ContactPage;

  return <Handler {...props} />;
};

// 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,
};
136
Q

Why we need to pass a function to setState()?

A

In React, setState() is a method used to update the state of a component. It is asynchronous and is used to notify React that the component’s state has changed and that it should re-render.

One of the important aspects of setState() is that it can take an optional second argument: a callback function. This callback function is invoked after setState() has been completed and the component has been re-rendered.

Here are a few reasons why passing a function to setState() might be necessary or advantageous:

Accessing Previous State: When updating state based on the previous state, it’s crucial to use a function as an argument in setState() instead of an object. This ensures that React provides the correct previous state. This is because React batches state updates for performance reasons, and the state value you’re referencing may not be the most recent if you’re using the object-based form of setState().

Example:

this.setState((prevState) => {
  return { count: prevState.count + 1 };
});

Batching State Updates: React batches state updates for better performance. If you call setState() multiple times in a synchronous manner, React will batch these updates together into a single update for better performance. Using the function form of setState() ensures that each update is applied correctly and isn’t overwritten by a subsequent update.

Callback after State Update: Sometimes you need to perform certain actions after the state has been updated and the component has re-rendered. Passing a callback function as the second argument to setState() allows you to execute code after the state has been updated.

Example:

this.setState({ count: this.state.count + 1 }, () => {
  console.log('State updated');
});

In summary, passing a function to setState() is essential for correctly updating state based on the previous state, ensuring proper batching of state updates, and executing code after the state has been updated.

137
Q

What are React Mixins?

A

React mixins were a feature of React.js that allowed developers to encapsulate reusable behavior and functionality, making it easier to share code between components. A mixin was essentially an object containing methods that could be mixed into a React component’s prototype, extending its capabilities.

Mixins provided a way to compose behavior in React components without using inheritance. They were often used for cross-cutting concerns such as event handling, state management, or other utilities. However, mixins also introduced certain complexities and potential issues, such as naming conflicts and difficulties in understanding component behavior due to the implicit nature of mixins.

Despite their usefulness, mixins were officially deprecated by the React team. The main reason for this deprecation was that mixins introduced unexpected behavior and made it difficult to reason about the component’s state and lifecycle. Instead, the React team encouraged the use of other patterns like higher-order components (HOCs), render props, and React hooks for achieving similar functionality in a more explicit and predictable manner.

As of the React version 16.3, mixins are no longer supported, and developers are encouraged to use alternative patterns provided by React itself or popular libraries in the ecosystem.

138
Q

Why is isMounted() an anti-pattern and what is the proper solution?

A

The primary use case for isMounted() is to avoid calling setState() after a component has been unmounted, because it will emit a warning.

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.

139
Q

What are the Pointer Events supported in React?

A

Pointer Events provide a unified way of handling all input events. In the old days we had a mouse and respective event listeners to handle them but nowadays we have many devices which don’t correlate to having a mouse, like phones with touch surface or pens. We need to remember that these events will only work in browsers that support the Pointer Events specification.

The following event types are now available in React DOM:

onPointerDown
onPointerMove
onPointerUp
onPointerCancel
onGotPointerCapture
onLostPointerCapture
onPointerEnter
onPointerLeave
onPointerOver
onPointerOut

140
Q

Why should component names start with capital letter?

A

If you are rendering your component using JSX, the name of that component has to begin with a capital letter otherwise React will throw an error as an unrecognized tag. This convention is because only HTML elements and SVG tags can begin with a lowercase letter.

class SomeComponent extends Component {
  // Code goes here
}

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:

class myComponent extends Component {
  render() {
    return <div />;
  }
}

export default myComponent;

While when imported in another file it should start with capital letter:

import MyComponent from “./myComponent”;
What are the exceptions on React component naming?
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)`
          )
    }
141
Q

Are custom DOM attributes supported in React v16?

A

Yes. In the past, React used to ignore unknown DOM attributes. If you wrote JSX with an attribute that React doesn’t recognize, React would just skip it.

For example, let’s take a look at the below attribute:

<div mycustomattribute={“something”} />

Would render an empty div to the DOM with React v15:

<div></div>

In React v16 any unknown attributes will end up in the DOM:

<div></div>

This is useful for supplying browser-specific non-standard attributes, trying new DOM APIs, and integrating with opinionated third-party libraries.

142
Q

What is the difference between constructor and getInitialState?

A

You should initialize state in the constructor when using ES6 classes, and getInitialState() method when using React.createClass().

Using ES6 classes:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      /* initial state */
    };
  }
}

Using React.createClass():

const MyComponent = React.createClass({
  getInitialState() {
    return {
      /* initial state */
    };
  },
});

Note: React.createClass() is deprecated and removed in React v16. Use plain JavaScript classes instead.

143
Q

Can you force a component to re-render without calling setState?

A

By default, when your component’s state or props change, your component will re-render. If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate().

component.forceUpdate(callback);
It is recommended to avoid all uses of forceUpdate() and only read from this.props and this.state in render().

144
Q

What is the difference between super() and super(props) in React using ES6 classes?

A

When you want to access this.props in constructor() then you should pass props to super() method.

Using super(props):

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    console.log(this.props); // { name: 'John', ... }
  }
}

Using super():

class MyComponent extends React.Component {
  constructor(props) {
    super();
    console.log(this.props); // undefined
  }
}

Outside constructor() both will display same value for this.props.

145
Q

How to loop inside JSX?

A

You can simply use Array.prototype.map with ES6 arrow function syntax.

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>

But you can’t iterate using for loop:

<tbody>
  for (let i = 0; i < items.length; i++) {
    <SomeComponent key={items[i].id} name={items[i].name} />
  }
</tbody>

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.

146
Q

How do you access props in attribute quotes?

A

React (or JSX) doesn’t support variable interpolation inside an attribute value. The below representation won’t work:

<img className="image" src="images/{this.props.image}" />

But you can put any JS expression inside curly braces as the entire attribute value. So the below expression works:

<img className="image" src={"images/" + this.props.image} />

Using template strings will also work:

<img className="image" src={`images/${this.props.image}`} />
147
Q

What is React proptype array with shape?

A

If you want to pass an array of objects to a component with a particular shape then use React.PropTypes.shape() as an argument to React.PropTypes.arrayOf().

ReactComponent.propTypes = {
  arrayWithShape: React.PropTypes.arrayOf(
    React.PropTypes.shape({
      color: React.PropTypes.string.isRequired,
      fontSize: React.PropTypes.number.isRequired,
    })
  ).isRequired,
};
148
Q

How to conditionally apply class attributes?

A

You shouldn’t use curly braces inside quotes because it is going to be evaluated as a string.

<div className="btn-panel {this.props.visible ? 'show' : 'hidden'}">

Instead you need to move curly braces outside (don't forget to include spaces between class names):
<div className={'btn-panel ' + (this.props.visible ? 'show' : 'hidden')}>

Template strings will also work:
<div className={`btn-panel ${this.props.visible ? 'show' : 'hidden'}`}>
149
Q

What is the difference between React and ReactDOM?

A

The react package contains React.createElement(), React.Component, React.Children, and other helpers related to elements and component classes. You can think of these as the isomorphic or universal helpers that you need to build components. The react-dom package contains ReactDOM.render(), and in react-dom/server we have server-side rendering support with ReactDOMServer.renderToString() and ReactDOMServer.renderToStaticMarkup().

150
Q

Why ReactDOM is separated from React?

A

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.

151
Q

How to use React label element?

A

If you try to render a <label> element bound to a text input using the standard for attribute, then it produces HTML missing that attribute and prints a warning to the console.</label>

<label for={'user'}>{'User'}</label>
<input type={'text'} id={'user'} />

Since for is a reserved keyword in JavaScript, use htmlFor instead.

<label htmlFor={'user'}>{'User'}</label>
<input type={'text'} id={'user'} />
152
Q

How to combine multiple inline style objects?

A

You can use spread operator in regular React:

<button style={{ ...styles.panel.button, ...styles.panel.submitButton }}>
  {"Submit"}
</button>

If you’re using React Native then you can use the array notation:

<button style={[styles.panel.button, styles.panel.submitButton]}>
  {"Submit"}
</button>
153
Q

How to re-render the view when the browser is resized?

A

You can use the useState hook to manage the width and height state variables, and the useEffect hook to add and remove the resize event listener. The [] dependency array passed to useEffect ensures that the effect only runs once (on mount) and not on every re-render.

import React, { useState, useEffect } from "react";
function WindowDimensions() {
  const [dimensions, setDimensions] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });

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

What is the difference between setState() and replaceState() methods?

A

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().

155
Q

How to listen to state changes?

A

In React, you can listen to state changes within a component by using lifecycle methods or React hooks, depending on whether you’re working with class components or functional components.

Class Components:
If you’re using class components, you can listen to state changes by implementing the componentDidUpdate lifecycle method. This method is called after the component’s state has been updated, providing an opportunity to perform actions in response to state changes.

Here’s an example of how you can use componentDidUpdate to listen to state changes:

import React, { Component } from 'react';

class MyComponent extends Component {
  componentDidUpdate(prevProps, prevState) {
    // Check if the state has changed
    if (this.state.someState !== prevState.someState) {
      // Perform actions based on state change
      console.log('State changed:', this.state.someState);
    }
  }

  render() {
    return <div>Your component content here</div>;
  }
}

Functional Components with React Hooks:
If you’re using functional components, you can use the useState hook to manage state and the useEffect hook to listen to state changes. You can use useEffect with an empty dependency array ([]) to listen to changes on mount or with specific state variables to listen to changes in those variables.

Here’s an example using useState and useEffect hooks:

import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [someState, setSomeState] = useState(initialValue);

  useEffect(() => {
    // This function will be called whenever `someState` changes
    console.log('State changed:', someState);
  }, [someState]); // Only re-run the effect if `someState` changes

  return <div>Your component content here</div>;
}

In both cases, you’re essentially setting up a mechanism to perform specific actions whenever the component’s state changes. Whether you’re using class components with componentDidUpdate or functional components with useState and useEffect, you have the ability to listen to state changes and respond accordingly within your components.

156
Q

What is the recommended approach of removing an array element in React state?

A

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)
  })
}
157
Q

Is it possible to use React without rendering HTML?

A

It is possible. Below are the possible options:

render() {
  return false
}
render() {
  return true
}
render() {
  return null
}

React version >=16.0.0:

render() {
  return []
}
render() {
  return ""
}

React version >=16.2.0:

render() {
  return <React.Fragment></React.Fragment>
}
render() {
  return <></>
}
React version >=18.0.0:

render() {
  return undefined
}
158
Q

How to pretty print JSON with React?

A

We can use <pre> tag so that the formatting of the JSON.stringify() is retained:

const data = { name: "John", age: 42 };

class User extends React.Component {
  render() {
    return <pre>{JSON.stringify(data, null, 2)}</pre>;
  }
}

React.render(<User />, document.getElementById("container"));
159
Q

Why you can’t update props in React?

A

The React philosophy is that props should be immutable and top-down. This means that a parent can send any prop values to a child, but the child can’t modify received props.

160
Q

How to focus an input element on page load?

A
import React, { useEffect, useRef } from "react";

const App = () => {
  const inputElRef = useRef(null);

  useEffect(() => {
    inputElRef.current.focus();
  }, []);

  return (
    <div>
      <input defaultValue={"Won't focus"} />
      <input ref={inputElRef} defaultValue={"Will focus"} />
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("app"));
161
Q

What are the possible ways of updating objects in state?

A

Calling setState() with an object to merge with state:

Using Object.assign() to create a copy of the object:

const user = Object.assign({}, this.state.user, { age: 42 });
this.setState({ user });
Using spread operator:

const user = { ...this.state.user, age: 42 };
this.setState({ user });
Calling setState() with a function:

this.setState((prevState) => ({
  user: {
    ...prevState.user,
    age: 42,
  },
}));
162
Q

What are the approaches to include polyfills in your create-react-app?

A

There are approaches to include polyfills in create-react-app,

Manual import from core-js:

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.

import “core-js/fn/array/find”;
import “core-js/fn/array/includes”;
import “core-js/fn/number/is-nan”;
Using Polyfill service:

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.

163
Q

How to use https instead of http in create-react-app?

A

You just need to use HTTPS=true configuration. You can edit your package.json scripts section:

"scripts": {
  "start": "set HTTPS=true && react-scripts start"
}

or just run set HTTPS=true && npm start

164
Q

How to avoid using relative path imports in create-react-app?

A

Create a file called .env in the project root and write the import path:

NODE_PATH=src/app
After that restart the development server. Now you should be able to import anything inside src/app without relative paths.

165
Q

How to add Google Analytics for React Router?

A

Add a listener on the history object to record each page view:

history.listen(function (location) {
  window.ga("set", "page", location.pathname + location.search);
  window.ga("send", "pageview", location.pathname + location.search);
});
166
Q

How to update a component every second?

A

You need to use setInterval() to trigger the change, but you also need to clear the timer when the component unmounts to prevent errors and memory leaks.

componentDidMount() {
  this.interval = setInterval(() => this.setState({ time: Date.now() }), 1000)
}

componentWillUnmount() {
  clearInterval(this.interval)
}
167
Q

How do you apply vendor prefixes to inline styles in React?

A

React does not apply vendor prefixes automatically. You need to add vendor prefixes manually.

<div
  style={{
    transform: "rotate(90deg)",
    WebkitTransform: "rotate(90deg)", // note the capital 'W' here
    msTransform: "rotate(90deg)", // 'ms' is the only lowercase vendor prefix
  }}
/>

A vendor prefix is a short string (usually a few letters) added to the beginning of a CSS property to ensure that it’s interpreted correctly by specific web browsers. These prefixes were introduced as a way for browser vendors to implement experimental or non-standard CSS features before they were finalized and standardized by the W3C (World Wide Web Consortium).

168
Q

How to import and export components using React and ES6?

A

You should use default for exporting the components

import React from "react";
import User from "user";

export default class MyProfile extends React.Component {
  render() {
    return <User type="customer">//...</User>;
  }
}

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.

169
Q

Why is a component constructor called only once?

A

React’s reconciliation algorithm assumes that without any information to the contrary, if a custom component appears in the same place on subsequent renders, it’s the same component as before, so reuses the previous instance rather than creating a new one.

170
Q

How to define constants in React?

A

You can use ES7 static field to define constant.

class MyComponent extends React.Component {
static DEFAULT_PAGINATION = 10;
}

171
Q

How to programmatically trigger click event in React?

A

You could use the ref prop to acquire a reference to the underlying HTMLInputElement object through a callback, store the reference as a class property, then use that reference to later trigger a click from your event handlers using the HTMLElement.click method.

This can be done in two steps:

Create ref in render method:

<input ref={(input) => (this.inputElement = input)} />
Apply click event in your event handler:

this.inputElement.click();
172
Q

What are the common folder structures for React?

A

There are two common practices for React project file structure.

Grouping by features or routes:

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
Grouping by file type:

Another popular way to structure projects is to group similar files together.

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

173
Q

What are the popular packages for animation?

A

React Transition Group and React Motion are popular animation packages in React ecosystem.

174
Q

What is the benefit of styles modules?

A

It is recommended to avoid hard coding style values in components. Any values that are likely to be used across different UI components should be extracted into their own modules.

For example, these styles could be extracted into a separate component:

export const colors = {
white,
black,
blue,
};

export const space = [0, 8, 16, 32, 64];
And then imported individually in other components:

import { space, colors } from “./styles”;

175
Q

What are the popular React-specific linters?

A

ESLint is a popular JavaScript linter. There are plugins available that analyse specific code styles. One of the most common for React is an npm package called eslint-plugin-react. By default, it will check a number of best practices, with rules checking things from keys in iterators to a complete set of prop types.

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.

176
Q

How to make AJAX call and in which component lifecycle methods should I make an AJAX call?

A

You can use AJAX libraries such as Axios, jQuery AJAX, and the browser built-in fetch. You should fetch data in the componentDidMount() lifecycle method. This is so you can use setState() to update your component when the data is retrieved.

For example, the employees list fetched from API and set local state:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      employees: [],
      error: null,
    };
  }

  componentDidMount() {
    fetch("https://api.example.com/items")
      .then((res) => res.json())
      .then(
        (result) => {
          this.setState({
            employees: result.employees,
          });
        },
        (error) => {
          this.setState({ error });
        }
      );
  }

  render() {
    const { error, employees } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else {
      return (
        <ul>
          {employees.map((employee) => (
            <li key={employee.name}>
              {employee.name}-{employee.experience}
            </li>
          ))}
        </ul>
      );
    }
  }
}
177
Q

What are render props?

A

Render Props is a simple technique for sharing code between components using a prop whose value is a function. The below component uses render prop which returns a React element.

<DataProvider render={(data) => <h1>{`Hello ${data.target}`}</h1>} />

Libraries such as React Router and DownShift are using this pattern.

178
Q

What is React Router?

A

React Router is a powerful routing library built on top of React that helps you add new screens and flows to your application incredibly quickly, all while keeping the URL in sync with what’s being displayed on the page.

179
Q

How React Router is different from history library?

A

React Router is a wrapper around the history library which handles interaction with the browser’s window.history with its browser and hash histories. It also provides memory history which is useful for environments that don’t have global history, such as mobile app development (React Native) and unit testing with Node.

180
Q

What are the <Router> components of React Router v4?

A

React Router v4 provides below 3 <Router> components:

<BrowserRouter>
<HashRouter>
<MemoryRouter>
The above components will create browser, hash, and memory history instances. React Router v4 makes the properties and methods of the history instance associated with your router available through the context in the router object.

181
Q

What is the purpose of push() and replace() methods of history?

A

A history instance has two methods for navigation purpose.

push()
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.

182
Q

How do you programmatically navigate using React Router v4 using the withRouter() higher-order function?

A

The withRouter() higher-order function will inject the history object as a prop of the component. This object provides push() and replace() methods to avoid the usage of context.

import { withRouter } from "react-router-dom"; // this also works with 'react-router-native'

const Button = withRouter(({ history }) => (
  <button
    type="button"
    onClick={() => {
      history.push("/new-location");
    }}
  >
    {"Click Me!"}
  </button>
));
183
Q

How do you programmatically navigate using React Router v4 using <Route> component and render props pattern?

A

The <Route> component passes the same props as withRouter(), so you will be able to access the history methods through the history prop.

import { Route } from "react-router-dom";

const Button = () => (
  <Route
    render={({ history }) => (
      <button
        type="button"
        onClick={() => {
          history.push("/new-location");
        }}
      >
        {"Click Me!"}
      </button>
    )}
  />
184
Q

Why you get “Router may have only one child element” warning?

A

The warning “Router may have only one child element” typically occurs in React applications when using a routing library like React Router. This warning is generated because the <Router> component expects to have only one child element directly nested within it.

For example, if you have code like this:

<Router>
  <Route path="/" component={Home} />
  <Route path="/about" component={About} />
</Router>

You would receive the warning because <Router> has two child elements (<Route> components). To resolve this warning, you can wrap your routes in a single parent element, like a <Switch> or a <div>. For example:

<Router>
  <Switch>
    <Route path="/" component={Home} />
    <Route path="/about" component={About} />
  </Switch>
</Router>

By wrapping the <Route> components in a <Switch> or a <div>, you ensure that <Router> has only one direct child element, thus eliminating the warning.

185
Q

How to pass params to history.push method in React Router v4?

A

While navigating you can pass props to the history object:

this.props.history.push({
  pathname: "/template",
  search: "?name=sudheer",
  state: { detail: response.data },
});

The search property is used to pass query params in push() method.

186
Q

How to implement default or NotFound page?

A

A <Switch> renders the first child <Route> that matches. A <Route> with no path always matches. So you just need to simply drop path attribute as below

<Switch>
  <Route exact path="/" component={Home} />
  <Route path="/user" component={User} />
  <Route component={NotFound} />
</Switch>
187
Q

How to get history on React Router v4?

A

Below are the list of steps to get history object on React Router v4,

Create a module that exports a history object and import this module across the project.

For example, create history.js file:

import { createBrowserHistory } from "history";

export default createBrowserHistory({
  /* pass a configuration object here if needed */
});

You should use the <Router> component instead of built-in routers. Import the above history.js inside index.js file:

import { Router } from "react-router-dom";
import history from "./history";
import App from "./App";

ReactDOM.render(
  <Router history={history}>
    <App />
  </Router>,
  holder
);

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");
188
Q

How to perform automatic redirect after login?

A

The react-router package provides <Redirect> component in React Router. Rendering a <Redirect> will navigate to a new location. Like server-side redirects, the new location will override the current location in the history stack.

import React, { Component } from "react";
import { Redirect } from "react-router";

export default class LoginComponent extends Component {
  render() {
    if (this.state.isLoggedIn === true) {
      return <Redirect to="/your/redirect/page" />;
    } else {
      return <div>{"Login Please"}</div>;
    }
  }
}
189
Q

What is React Intl?

A

The React Intl library makes internationalization in React straightforward, with off-the-shelf components and an API that can handle everything from formatting strings, dates, and numbers, to pluralization. React Intl is part of FormatJS which provides bindings to React via its components and API.

190
Q

What are the main features of React Intl?

A

Below are the main features of React Intl,

  1. Display numbers with separators.
  2. Display dates and times correctly.
  3. Display dates relative to “now”.
  4. Pluralize labels in strings.
  5. Support for 150+ languages.
  6. Runs in the browser and Node.
  7. Built on standards.
191
Q

What are the two ways of formatting in React Intl?

A

In React Intl, there are primarily two ways of formatting: using <FormattedMessage> component and using the intl object directly.

**Using <FormattedMessage> Component:
**The <FormattedMessage> component is provided by React Intl to format messages within your components. It allows you to define messages with placeholders for dynamic values and then format them using the <FormattedMessage> component. Here’s an example:

import React from 'react';
import { FormattedMessage } from 'react-intl';

function MyComponent() {
  return (
    <div>
      <FormattedMessage
        id="myMessage"
        defaultMessage="Hello, {name}!"
        values={{ name: 'World' }}
      />
    </div>
  );
}

export default MyComponent;

In this example, the <FormattedMessage> component formats the message with the id “myMessage”, with a default message “Hello, {name}!”, and replaces the placeholder {name} with the value provided in the values prop.

**Using intl Object Directly:
**The intl object is an instance of IntlProvider provided by React Intl, which can be accessed directly in your components using the useIntl() hook or the injectIntl() higher-order component. Once you have access to the intl object, you can use its methods to format messages. Here’s an example:

import React from 'react';
import { useIntl } from 'react-intl';

function MyComponent() {
  const intl = useIntl();
  const name = 'World';
  const message = intl.formatMessage({ id: 'myMessage' }, { name });

  return <div>{message}</div>;
}

export default MyComponent;

In this example, the useIntl() hook is used to access the intl object, and then the formatMessage() method is used to format the message with the id “myMessage” and replace the {name} placeholder with the value provided.

Both methods are commonly used in React Intl applications, and the choice between them depends on your specific use case and preference.

192
Q

How to access current locale with React Intl?

A

You can get the current locale in any component of your application using injectIntl():

import { injectIntl, intlShape } from "react-intl";

const MyComponent = ({ intl }) => (
  <div>{`The current locale is ${intl.locale}`}</div>
);

MyComponent.propTypes = {
  intl: intlShape.isRequired,
};

export default injectIntl(MyComponent);
193
Q

How to format date using React Intl?

A

The injectIntl() higher-order component will give you access to the formatDate() method via the props in your component. The method is used internally by instances of FormattedDate and it returns the string representation of the formatted date.

import { injectIntl, intlShape } from "react-intl";

const stringDate = this.props.intl.formatDate(date, {
  year: "numeric",
  month: "numeric",
  day: "numeric",
});

const MyComponent = ({ intl }) => (
  <div>{`The formatted date is ${stringDate}`}</div>
);

MyComponent.propTypes = {
  intl: intlShape.isRequired,
};

export default injectIntl(MyComponent);
194
Q

What is Shallow Renderer in React testing?

A

Shallow rendering is useful for writing unit test cases in React. It lets you render a component one level deep and assert facts about what its render method returns, without worrying about the behavior of child components, which are not instantiated or rendered.

For example, if you have the following component:

function MyComponent() {
  return (
    <div>
      <span className={"heading"}>{"Title"}</span>
      <span className={"description"}>{"Description"}</span>
    </div>
  );
}

Then you can assert as follows:

import ShallowRenderer from "react-test-renderer/shallow";

// in your test
const renderer = new ShallowRenderer();
renderer.render(<MyComponent />);

const result = renderer.getRenderOutput();

expect(result.type).toBe("div");
expect(result.props.children).toEqual([
  <span className={"heading"}>{"Title"}</span>,
  <span className={"description"}>{"Description"}</span>,
]);
195
Q

What is TestRenderer package in React?

A

This package provides a renderer that can be used to render components to pure JavaScript objects, without depending on the DOM or a native mobile environment. This package makes it easy to grab a snapshot of the platform view hierarchy (similar to a DOM tree) rendered by a ReactDOM or React Native without using a browser or jsdom.

import TestRenderer from "react-test-renderer";

const Link = ({ page, children }) => <a href={page}>{children}</a>;

const testRenderer = TestRenderer.create(
  <Link page={"https://www.facebook.com/"}>{"Facebook"}</Link>
);

console.log(testRenderer.toJSON());
// {
//   type: 'a',
//   props: { href: 'https://www.facebook.com/' },
//   children: [ 'Facebook' ]
// }
196
Q

What is the purpose of ReactTestUtils package?

A

ReactTestUtils are provided in the with-addons package and allow you to perform actions against a simulated DOM for the purpose of unit testing.

197
Q

What are the advantages of Jest over Jasmine?

A

There are couple of advantages compared to Jasmine:

  1. Automatically finds tests to execute in your source code.
  2. Automatically mocks dependencies when running your tests.
  3. Allows you to test asynchronous code synchronously.
  4. Runs your tests with a fake DOM implementation (via jsdom) so that your tests can be run on the command line.
  5. Runs tests in parallel processes so that they finish sooner.
198
Q

Give a simple example of Jest test case

A

Let’s write a test for a function that adds two numbers in sum.js file:

const sum = (a, b) => a + b;

export default sum;
Create a file named sum.test.js which contains actual test:

import sum from "./sum";

test("adds 1 + 2 to equal 3", () => {
  expect(sum(1, 2)).toBe(3);
});
And then add the following section to your package.json:

{
  "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)
199
Q

What is flux?

A

Flux is an application design paradigm used as a replacement for the more traditional MVC pattern. It is not a framework or a library but a new kind of architecture that complements React and the concept of Unidirectional Data Flow. Facebook uses this pattern internally when working with React.

The workflow between dispatcher, stores and views components with distinct inputs and outputs as follows:

200
Q

What are the core principles of Redux?

A

Redux follows three fundamental principles:

  1. Single source of truth: The state of your whole application is stored in an object tree within a single store. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.
  2. 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.
  3. Changes are made with pure functions: To specify how the state tree is transformed by actions, you write reducers. Reducers are just pure functions that take the previous state and an action as parameters, and return the next state.
201
Q

What are the downsides of Redux compared to Flux?

A

Instead of saying downsides we can say that there are few compromises of using Redux over Flux. Those are as follows:

  1. 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.
  2. 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.
  3. There is no nice Flow integration yet: Flux currently lets you do very impressive static type checks which Redux doesn’t support yet.
202
Q

Can I dispatch an action in reducer?

A

Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.

203
Q

How to access Redux store outside a component?

A

You just need to export the store from the module where it created with createStore(). Also, it shouldn’t pollute the global window object.

store = createStore(myReducer);

export default store;
204
Q

Are there any similarities between Redux and RxJS?

A

These libraries are very different for very different purposes, but there are some vague similarities.

Redux is a tool for managing state throughout the application. It is usually used as an architecture for UIs. Think of it as an alternative to (half of) Angular. RxJS is a reactive programming library. It is usually used as a tool to accomplish asynchronous tasks in JavaScript. Think of it as an alternative to Promises. Redux uses the Reactive paradigm because the Store is reactive. The Store observes actions from a distance, and changes itself. RxJS also uses the Reactive paradigm, but instead of being an architecture, it gives you basic building blocks, Observables, to accomplish this pattern.

205
Q

How to dispatch an action on load?

A
import React, { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { someAction } from './actions';

const MyComponent = () => {
  const dispatch = useDispatch();

  useEffect(() => {
    // Dispatching an action when the component mounts
    dispatch(someAction());
  }, []); // Empty dependency array ensures the effect runs only once

  return (
    <div>
      {/* Your component JSX */}
    </div>
  );
};

export default MyComponent;
206
Q

How to use connect() from React Redux?

A

connect() is a higher-order component provided by React Redux that connects your React components to a Redux store. It is typically used to access Redux state and dispatch actions from within your components.

Here’s how you can use connect():

  1. Define mapStateToProps: This function allows you to specify which parts of the Redux state should be mapped to props in your component.
  2. Define mapDispatchToProps: This function allows you to specify which action creators should be mapped to props in your component.
  3. Call connect(): Pass mapStateToProps and mapDispatchToProps as arguments to connect().
import React from 'react';
import { connect } from 'react-redux';
import { someAction } from './actions';

// Define mapStateToProps
const mapStateToProps = (state) => ({
  // Define props that should be derived from Redux state
  someData: state.someData,
});

// Define mapDispatchToProps
const mapDispatchToProps = (dispatch) => ({
  // Define props that should dispatch actions
  doSomething: () => dispatch(someAction()),
});

// Define your component
const MyComponent = ({ someData, doSomething }) => (
  <div>
    <p>{someData}</p>
    <button onClick={doSomething}>Do Something</button>
  </div>
);

// Connect your component
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
207
Q

How to reset state in Redux?

A

In Redux, to reset the state, you typically dispatch an action that resets the state to its initial values. You can achieve this by creating a special “reset” action type and a corresponding reducer case that returns the initial state.

Here’s how you can reset the state in Redux:

  1. Define a reset action type: Create a constant for the action type, e.g., RESET_STATE.
  2. Define a reset action creator: Create an action creator function that returns an action with the type RESET_STATE.
  3. Update your reducer: Add a case to your reducer that handles the RESET_STATE action type and returns the initial state.

Here’s an example implementation:

// Action Types
const RESET_STATE = 'RESET_STATE';

// Action Creators
export const resetState = () => ({
  type: RESET_STATE,
});

// Reducer
const initialState = {
  // Define your initial state here
};

const rootReducer = (state = initialState, action) => {
  switch (action.type) {
    case RESET_STATE:
      return initialState;
    // Add other cases for your existing actions
    default:
      return state;
  }
};

export default rootReducer;
208
Q

Should I keep all component’s state in Redux store?

A

Keep your data in the Redux store, and the UI related state internally in the component.

209
Q

What is the proper way to access Redux store?

A

**Hooks (useSelector and useDispatch): **With the introduction of hooks in React, Redux also provides hooks like useSelector and useDispatch to access the Redux store directly within functional components.

Example:

import { useSelector, useDispatch } from 'react-redux';

const MyComponent = () => {
  const someValue = useSelector(state => state.someValue);
  const dispatch = useDispatch();

  // Dispatch actions when needed
  const handleClick = () => {
    dispatch(someAction());
  };

  return (
    <div>
      <p>{someValue}</p>
      <button onClick={handleClick}>Dispatch Action</button>
    </div>
  );
};

export default MyComponent;

Using getState: In non-component code (e.g., middleware, thunks), you can access the Redux store directly using the getState method provided by the store.

Example:

import store from './store'; // Assuming your Redux store is defined here

const currentState = store.getState();

These are the most common ways to access the Redux store depending on your use case and whether you’re working with class components, functional components, or non-component code.

210
Q

What is the difference between component and container in React Redux?

A

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.

211
Q

What is the purpose of the constants in Redux?

A

Constants allows you to easily find all usages of that specific functionality across the project when you use an IDE. It also prevents you from introducing silly bugs caused by typos – in which case, you will get a ReferenceError immediately.

Normally we will save them in a single file (constants.js or actionTypes.js).

export const ADD_TODO = “ADD_TODO”;
export const DELETE_TODO = “DELETE_TODO”;
export const EDIT_TODO = “EDIT_TODO”;
export const COMPLETE_TODO = “COMPLETE_TODO”;
export const COMPLETE_ALL = “COMPLETE_ALL”;
export const CLEAR_COMPLETED = “CLEAR_COMPLETED”;
In Redux, you use them in two places:

During action creation:

Let’s take actions.js:

import { ADD_TODO } from "./actionTypes";

export function addTodo(text) {
  return { type: ADD_TODO, text };
}

In reducers:
Let’s create reducer.js:

import { ADD_TODO } from "./actionTypes";

export default (state = [], action) => {
  switch (action.type) {
    case ADD_TODO:
      return [
        ...state,
        {
          text: action.text,
          completed: false,
        },
      ];
    default:
      return state;
  }
};
212
Q

How to structure Redux top level directories?

A

Most of the applications has several top-level directories as below:

  1. Components: Used for dumb components unaware of Redux.
  2. Containers: Used for smart components connected to Redux.
  3. Actions: Used for all action creators, where file names correspond to part of the app.
  4. Reducers: Used for all reducers, where files name correspond to state key.
  5. Store: Used for store initialization.

This structure works well for small and medium size apps.

213
Q

What is redux-saga?

A

redux-saga is a library that aims to make side effects (asynchronous things like data fetching and impure things like accessing the browser cache) in React/Redux applications easier and better.

214
Q

What is the mental model of redux-saga?

A

Saga is like a separate thread in your application, that’s solely responsible for side effects. redux-saga is a redux middleware, which means this thread can be started, paused and cancelled from the main application with normal Redux actions, it has access to the full Redux application state and it can dispatch Redux actions as well.

215
Q

What is Express Middleware?

A

Middleware in Express are functions that come into play after the server receives the request and before the response is sent to the client. They are arranged in a chain and are called in sequence.

We can use middleware functions for different types of processing tasks required for fulfilling the request like database querying, making API calls, preparing the response, etc, and finally calling the next middleware function in the chain.

Middleware functions take three arguments: the request object (request), the response object (response), and optionally the next() middleware function:

const express = require('express');
const app = express();
function middlewareFunction(request, response, next){
  ...
  next()
}

app.use(middlewareFunction)

An exception to this rule is error handling middleware which takes an error object as the fourth parameter. We call app.use() to add a middleware function to our Express application.

Under the hood, when we call app.use(), the Express framework adds our middleware function to its internal middleware stack. Express executes middleware in the order they are added, so if we make the calls in this order:

app.use(function1)
app.use(function2)
Express will first execute function1 and then function2.

216
Q

What is Redux DevTools?

A

Redux DevTools is a live-editing time travel environment for Redux with hot reloading, action replay, and customizable UI. If you don’t want to bother with installing Redux DevTools and integrating it into your project, consider using Redux DevTools Extension for Chrome and Firefox.

217
Q

What are the features of Redux DevTools?

A

Some of the main features of Redux DevTools are below,

  1. Lets you inspect every state and action payload.
  2. Lets you go back in time by cancelling actions.
  3. If you change the reducer code, each staged action will be re-evaluated.
  4. If the reducers throw, you will see during which action this happened, and what the error was.
  5. With persistState() store enhancer, you can persist debug sessions across page reloads.
218
Q

What are Redux selectors and why to use them?

A

In Redux, selectors are functions that are used to extract specific pieces of data from the Redux store. They provide an abstraction layer on top of the state structure, allowing components to access data from the store in a more convenient and efficient manner. Selectors are typically used to compute derived data or to extract a subset of the state for use in a component.

Here’s a basic example of a selector function in Redux:

// Selector function to get a specific piece of data from the Redux store
const getTodoById = (state, todoId) => {
  return state.todos.find(todo => todo.id === todoId);
};

In this example, getTodoById is a selector function that takes the Redux state and a todoId as parameters, and returns the todo object with the matching id from the todos array in the state.

Selectors are often used in conjunction with libraries like reselect, which provides memoized selector functions. Memoization ensures that the selector function only recalculates its value when its input parameters change, which can improve performance by preventing unnecessary re-renders of components.

Selectors help to keep the Redux-related logic separate from the components, making the codebase easier to maintain and test. They also promote reusability by allowing multiple components to use the same selector to access the same piece of data from the store.

219
Q

What is Redux Form?

A

Redux Form works with React and Redux to enable a form in React to use Redux to store all of its state. Redux Form can be used with raw HTML5 inputs, but it also works very well with common UI frameworks like Material UI, React Widgets and React Bootstrap.

220
Q

How to add multiple middlewares to Redux?

A

You can use applyMiddleware().

For example, you can add redux-thunk and logger passing them as arguments to applyMiddleware():

import { createStore, applyMiddleware } from "redux";
const createStoreWithMiddleware = applyMiddleware(
  ReduxThunk,
  logger
)(createStore);
221
Q

How to set initial state in Redux?

A

You need to pass initial state as second argument to createStore:

const rootReducer = combineReducers({
  todos: todos,
  visibilityFilter: visibilityFilter,
});

const initialState = {
  todos: [{ id: 123, name: "example", completed: false }],
};

const store = createStore(rootReducer, initialState);
222
Q

What is reselect and how it works?

A

Reselect is a selector library (for Redux) which uses memoization concept. It was originally written to compute derived data from Redux-like applications state, but it can’t be tied to any architecture or library.

Reselect keeps a copy of the last inputs/outputs of the last call, and recomputes the result only if one of the inputs changes. If the the same inputs are provided twice in a row, Reselect returns the cached output. It’s memoization and cache are fully customizable.

223
Q

What is Flow?

A

Flow is a static type checker designed to find type errors in JavaScript. Flow types can express much more fine-grained distinctions than traditional type systems. For example, Flow helps you catch errors involving null, unlike most type systems.

224
Q

What is the difference between Flow and PropTypes?

A

Flow is a static analysis tool (static checker) which uses a superset of the language, allowing you to add type annotations to all of your code and catch an entire class of bugs at compile time.

PropTypes is a basic type checker (runtime checker) which has been patched onto React. It can’t check anything other than the types of the props being passed to a given component. If you want more flexible typechecking for your entire project Flow/TypeScript are appropriate choices.

225
Q

How to use Font Awesome icons in React?

A

The below steps followed to include Font Awesome in React:

Install font-awesome:

$ npm install --save font-awesome
Import font-awesome in your index.js file:

import "font-awesome/css/font-awesome.min.css";
Add Font Awesome classes in className:

render() {
  return <div><i className={'fa fa-spinner'} /></div>
}
226
Q

What is React Dev Tools?

A

React Developer Tools let you inspect the component hierarchy, including component props and state. It exists both as a browser extension (for Chrome and Firefox), and as a standalone app (works with other environments including Safari, IE, and React Native).

The official extensions available for different browsers or environments.

Chrome extension
Firefox extension
Standalone app (Safari, React Native, etc)

227
Q

What are Styled Components?

A

Styled Components is a library for React and React Native that allows you to write CSS code directly in your JavaScript files. It enables you to create encapsulated and reusable styling components that are directly associated with your React components.

Benefits:

  1. Encapsulation: Styles are scoped to their respective components, avoiding global namespace clashes.
  2. Dynamic Styling: You can use props or other JavaScript expressions to dynamically generate styles.
  3. Easy Theming: Styled Components makes theming straightforward by allowing you to pass theme objects directly into styled components.
  4. Better Developer Experience: Writing styles in JavaScript provides better tooling support, like syntax highlighting, auto-completion, and static analysis.
228
Q

Give an example of Styled Components?

A

Lets create <Title> and <Wrapper> components with specific styles for each.

import React from "react";
import styled from "styled-components";

// 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>
229
Q

Can Redux only be used with React?

A

Redux can be used as a data store for any UI layer. The most common usage is with React and React Native, but there are bindings available for Angular, Angular 2, Vue, Mithril, and more. Redux simply provides a subscription mechanism which can be used by any other code.

230
Q

Do you need to have a particular build tool to use Redux?

A

Redux is originally written in ES6 and transpiled for production into ES5 with Webpack and Babel. You should be able to use it regardless of your JavaScript build process. Redux also offers a UMD build that can be used directly without any build process at all.

231
Q

How React PropTypes allow different types for one prop?

A

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]),
};
232
Q

Can I import an SVG file as react component?

A

You can import SVG directly as component instead of loading it as a file. This feature is available with react-scripts@2.0.0 and higher.

import { ReactComponent as Logo } from "./logo.svg";

const App = () => (
  <div>
    {/* Logo is an actual react component */}
    <Logo />
  </div>
);

Note: Don’t forget about the curly braces in the import.

233
Q

What is render hijacking in react?

A

The concept of render hijacking is the ability to control what a component will output from another component. It means that you decorate your component by wrapping it into a Higher-Order component. By wrapping, you can inject additional props or make other changes, which can cause changing logic of rendering. It does not actually enable hijacking, but by using HOC you make your component behave differently.

234
Q

How to pass numbers to React component?

A

You should be passing the numbers via curly braces({}) where as strings in quotes

React.render(
  <User age={30} department={"IT"} />,
  document.getElementById("container")
);
235
Q

Do I need to keep all my state into Redux? Should I ever use react internal state?

A

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

  1. Do other parts of the application care about this data?
  2. Do you need to be able to create further derived data based on this original data?
  3. Is the same data being used to drive multiple components?
  4. Is there value to you in being able to restore this state to a given point in time (ie, time travel debugging)?
  5. Do you want to cache the data (i.e, use what’s in state if it’s already there instead of re-requesting it)?
236
Q

What is the purpose of registerServiceWorker in React?

A

React creates a service worker for you without any configuration by default. The service worker is a web API that helps you cache your assets and other files so that when the user is offline or on a slow network, he/she can still see results on the screen, as such, it helps you build a better user experience, that’s what you should know about service worker for now. It’s all about adding offline capabilities to your site.

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import registerServiceWorker from "./registerServiceWorker";

ReactDOM.render(<App />, document.getElementById("root"));
registerServiceWorker();
237
Q

What is React lazy function?

A

The React.lazy function lets you render a dynamic import as a regular component. It will automatically load the bundle containing the OtherComponent when the component gets rendered. This must return a Promise which resolves to a module with a default export containing a React component.

const OtherComponent = React.lazy(() => import("./OtherComponent"));

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.

238
Q

How to prevent unnecessary updates using setState?

A

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.

For example, the user profile information is conditionally rendered as follows,

getUserProfile = (user) => {
  const latestAddress = user.address;
  this.setState((state) => {
    if (state.address === latestAddress) {
      return null;
    } else {
      return { title: latestAddress };
    }
  });
};
239
Q

How do you render Array in React 16 Version?

A

Unlike older releases, you don’t need to make sure render method return a single element in React16. You are able to return multiple sibling elements without a wrapping element by returning an array.

For example, let us take the below list of developers,

const ReactJSDevs = () => {
  return [
    <li key="1">John</li>,
    <li key="2">Jackie</li>,
    <li key="3">Jordan</li>,
  ];
};

You can also merge this array of items in another array component.

const JSDevs = () => {
  return (
    <ul>
      <li>Brad</li>
      <li>Brodge</li>
      <ReactJSDevs />
      <li>Brandon</li>
    </ul>
  );
};
240
Q

What are hooks?

A

Hooks is a special JavaScript function that allows you use state and other React features without writing a class. This pattern has been introduced as a new feature in React 16.8 and helped to isolate the stateful logic from the components.

Note: Hooks can be used inside an existing function component without rewriting the component.

241
Q

What rules need to be followed for hooks?

A

You need to follow two rules in order to use hooks,

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.

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.

242
Q

What are the benefits of React Router V4?

A

Below are the main benefits of React Router V4 module,

  1. 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>).
  2. You don’t need to manually set history. The router module will take care history by wrapping routes with <BrowserRouter> component.
    The application size is reduced by adding only the specific router module(Web, core, or native)
243
Q

In which scenarios error boundaries do not catch errors?

A

Below are the cases in which error boundaries doesn’t work,

  1. Inside Event handlers
  2. Asynchronous code using setTimeout or requestAnimationFrame callbacks
  3. During Server side rendering
  4. When errors thrown in the error boundary code itself
244
Q

Why do you not need error boundaries for event handlers?

A

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:

245
Q

What is the difference between try catch block and error boundaries?

A

Try catch block works with imperative code whereas error boundaries are meant for declarative code to render on the screen.

For example, the try catch block used for below imperative code

try {
  showButton();
} catch (error) {
  // ...
}

Whereas error boundaries wrap declarative code as below,

<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>

So if an error occurs in a componentDidUpdate method caused by a setState somewhere deep in the tree, it will still correctly propagate to the closest error boundary.

246
Q

What is the behavior of uncaught errors in react 16?

A

In React 16, errors that were not caught by any error boundary will result in unmounting of the whole React component tree. The reason behind this decision is that it is worse to leave corrupted UI in place than to completely remove it. For example, it is worse for a payments app to display a wrong amount than to render nothing.

247
Q

What is the proper placement for error boundaries?

A

The granularity of error boundaries usage is up to the developer based on project needs. You can follow either of these approaches,
1. You can wrap top-level route components to display a generic error message for the entire application.
2. You can also wrap individual components in an error boundary to protect them from crashing the rest of the application.

248
Q

What is the benefit of component stack trace from error boundary?

A

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,

249
Q

What is the required method to be defined for a class component?

A

The render() method is the only required method in a class component. i.e, All methods other than render method are optional for a class component.

250
Q

What are the possible return types of render method?

A

Below are the list of following types used and return from render method,

  1. React elements: Elements that instruct React to render a DOM node. It includes html elements such as <div/> and user defined elements.
  2. Arrays and fragments: Return multiple elements to render as Arrays and Fragments to wrap multiple elements
  3. Portals: Render children into a different DOM subtree.
  4. String and numbers: Render both Strings and Numbers as text nodes in the DOM
  5. Booleans or null: Doesn’t render anything but these types are used to conditionally render content.
251
Q

What is the main purpose of constructor?

A

The constructor is mainly used for two purposes,

  1. To initialize local state by assigning object to this.state
  2. For binding event handler methods to the instance For example, the below code covers both the above cases,
constructor(props) {
  super(props);
  // Don't call this.setState() here!
  this.state = { counter: 0 };
  this.handleClick = this.handleClick.bind(this);
}
252
Q

Is it mandatory to define constructor for React component?

A

No, it is not mandatory. i.e, If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.

253
Q

What are default props?

A

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.

import React from 'react';

const MyComponent = ({ prop1 = 'default1', prop2 = 'default2' }) => {
  // Use prop1 and prop2 as needed
  return (
    <div>
      <p>{prop1}</p>
      <p>{prop2}</p>
    </div>
  );
};

export default MyComponent;
254
Q

Why should not call setState in componentWillUnmount?

A

You should not call setState() in componentWillUnmount() because once a component instance is unmounted, it will never be mounted again.

255
Q

What is the methods order when component re-rendered?

A

An update can be caused by changes to props or state. The below methods are called in the following order when a component is being re-rendered.

static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()

256
Q

What is code-splitting?

A

Code-Splitting is a feature supported by bundlers like Webpack and Browserify which can create multiple bundles that can be dynamically loaded at runtime. The react project supports code splitting via dynamic import() feature.

For example, in the below code snippets, it will make moduleA.js and all its unique dependencies as a separate chunk that only loads after the user clicks the ‘Load’ button. moduleA.js

const moduleA = "Hello";

export { moduleA };
App.js

import React, { Component } from "react";

class App extends Component {
  handleClick = () => {
    import("./moduleA")
      .then(({ moduleA }) => {
        // Use moduleA
      })
      .catch((err) => {
        // Handle failure
      });
  };

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>Load</button>
      </div>
    );
  }
}

export default App;
257
Q

Does React support all HTML attributes?

A

As of React 16, both standard or custom DOM attributes are fully supported. Since React components often take both custom and DOM-related props, React uses the camelCase convention just like the DOM APIs.

Let us take few props with respect to standard HTML attributes,

<div tabIndex="-1" />      // Just like node.tabIndex DOM API
<div className="Button" /> // Just like node.className DOM API
<input readOnly={true} />  // Just like node.readOnly DOM API

These props work similarly to the corresponding HTML attributes, with the exception of the special cases. It also support all SVG attributes.

258
Q

What is NextJS and major features of it?

A

Next.js is a popular and lightweight framework for static and server‑rendered applications built with React. It also provides styling and routing solutions. Below are the major features provided by NextJS,

  1. Server-rendered by default
  2. Automatic code splitting for faster page loads
  3. Simple client-side routing (page based)
  4. Webpack-based dev environment which supports (HMR)
  5. Able to implement with Express or any other Node.js HTTP server
  6. Customizable with your own Babel and Webpack configurations
259
Q

Is it good to use arrow functions in render methods?

A

Yes, You can use. It is often the easiest way to pass parameters to callback functions. But you need to optimize the performance while using it.

class Foo extends Component {
  handleClick() {
    console.log("Click happened");
  }
  render() {
    return <button onClick={() => this.handleClick()}>Click Me</button>;
  }
}

Note: Using an arrow function in render method creates a new function each time the component renders, which may have performance implications

260
Q

How to prevent a function from being called multiple times?

A

If you use an event handler such as onClick or onScroll and want to prevent the callback from being fired too quickly, then you can limit the rate at which callback is executed. This can be achieved in the below possible ways,

  1. Throttling: Changes based on a time based frequency. For example, it can be used using _.throttle lodash function
  2. Debouncing: Publish changes after a period of inactivity. For example, it can be used using _.debounce lodash function
  3. RequestAnimationFrame throttling: Changes based on requestAnimationFrame. For example, it can be used using raf-schd lodash function
261
Q

How JSX prevents Injection Attacks?

A

React DOM escapes any values embedded in JSX before rendering them. Thus it ensures that you can never inject anything that’s not explicitly written in your application. Everything is converted to a string before being rendered.

For example, you can embed user input as below,

const name = response.potentiallyMaliciousInput;
const element = <h1>{name}</h1>;

This way you can prevent XSS(Cross-site-scripting) attacks in the application.

262
Q

How do you say that props are readonly?

A

When you declare a component as a function or a class, it must never modify its own props.

Let us take a below capital function,

function capital(amount, interest) {
  return amount + interest;
}

The above function is called “pure” because it does not attempt to change their inputs, and always return the same result for the same inputs. Hence, React has a single rule saying “All React components must act like pure functions with respect to their props.”

263
Q

What are the conditions to safely use the index as a key?

A

There are three conditions to make sure, it is safe use the index as a key.

  1. The list and items are static– they are not computed and do not change
  2. The items in the list have no ids
  3. The list is never reordered or filtered.
264
Q

Should keys be globally unique?

A

The keys used within arrays should be unique among their siblings but they don’t need to be globally unique. i.e, You can use the same keys with two different arrays.

265
Q

Why are you not required to use inheritance?

A

In React, it is recommended to use composition over inheritance to reuse code between components. Both Props and composition give you all the flexibility you need to customize a component’s look and behavior explicitly and safely. Whereas, If you want to reuse non-UI functionality between components, it is suggested to extract it into a separate JavaScript module. Later components import it and use that function, object, or class, without extending it.

266
Q

What is suspense component?

A

If the module containing the dynamic import is not yet loaded by the time parent component renders, you must show some fallback content while you’re waiting for it to load using a loading indicator. This can be done using Suspense component.

For example, the below code uses suspense component,

const OtherComponent = React.lazy(() => import("./OtherComponent"));

function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <OtherComponent />
      </Suspense>
    </div>
  );
}

As mentioned in the above code, Suspense is wrapped above the lazy component.

267
Q

What is route based code splitting?

A

One of the best place to do code splitting is with routes. The entire page is going to re-render at once so users are unlikely to interact with other elements in the page at the same time. Due to this, the user experience won’t be disturbed.

Let us take an example of route based website using libraries like React Router with React.lazy,

import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import React, { Suspense, lazy } from "react";

const Home = lazy(() => import("./routes/Home"));
const About = lazy(() => import("./routes/About"));

const App = () => (
  <Router>
    <Suspense fallback={<div>Loading...</div>}>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
      </Switch>
    </Suspense>
  </Router>
);

In the above code, the code splitting will happen at each route level.

268
Q

Is it possible to use react without JSX?

A

Yes, JSX is not mandatory for using React. Actually it is convenient when you don’t want to set up compilation in your build environment. Each JSX element is just syntactic sugar for calling React.createElement(component, props, …children).

For example, let us take a greeting example with JSX,

class Greeting extends React.Component {
  render() {
    return <div>Hello {this.props.message}</div>;
  }
}

ReactDOM.render(
  <Greeting message="World" />,
  document.getElementById("root")
);
You can write the same code without JSX as below,

class Greeting extends React.Component {
  render() {
    return React.createElement("div", null, `Hello ${this.props.message}`);
  }
}

ReactDOM.render(
  React.createElement(Greeting, { message: "World" }, null),
  document.getElementById("root")
);
269
Q

What is diffing algorithm?

A

React needs to use algorithms to find out how to efficiently update the UI to match the most recent tree. The diffing algorithms is generating the minimum number of operations to transform one tree into another. However, the algorithms have a complexity in the order of O(n³) where n is the number of elements in the tree.

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:

  1. Two elements of different types will produce different trees.
  2. The developer can hint at which child elements may be stable across different renders with a key prop.
270
Q

When do you need to use refs?

A

There are few use cases to go for refs,

Managing focus, text selection, or media playback.
Triggering imperative animations.
Integrating with third-party DOM libraries.

271
Q

What is the typical use case of portals?

A

React portals are very useful when a parent component has overflow: hidden or has properties that affect the stacking context (e.g. z-index, position, opacity) and you need to visually “break out” of its container.

For example, dialogs, global message notifications, hovercards, and tooltips.

272
Q

Is it recommended to use CSS In JS technique in React?

A

React does not have any opinion about how styles are defined but if you are a beginner then good starting point is to define your styles in a separate *.css file as usual and refer to them using className. This functionality is not part of React but came from third-party libraries. But If you want to try a different approach(CSS-In-JS) then styled-components library is a good option.

273
Q

Do I need to rewrite all my class components with hooks?

A

No. But you can try Hooks in a few components(or new components) without rewriting any existing code. Because there are no plans to remove classes in ReactJS.

274
Q
A

The effect hook called useEffect can be used to fetch data from an API and to set the data in the local state of the component with the useState hook’s update function.

Here is an example of fetching a list of react articles from an API using fetch.

import React from "react";

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

export default App;

A popular way to simplify this is by using the library axios.

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.

275
Q

Is Hooks cover all use cases for classes?

A

Hooks doesn’t cover all use cases of classes but there is a plan to add them soon. Currently there are no Hook equivalents to the uncommon getSnapshotBeforeUpdate and componentDidCatch lifecycles yet.

276
Q

Why do we use array destructuring (square brackets notation) in useState?

A

When we declare a state variable with useState, it returns a pair — an array with two items. The first item is the current value, and the second is a function that updates the value. Using [0] and [1] to access them is a bit confusing because they have a specific meaning. This is why we use array destructuring instead.

For example, the array index access would look as follows:

var userStateVariable = useState("userProfile"); // Returns an array pair
var user = userStateVariable[0]; // Access first item
var setUser = userStateVariable[1]; // Access second item
Whereas with array destructuring the variables can be accessed as follows:

const [user, setUser] = useState("userProfile");
277
Q

What are typical middleware choices for handling asynchronous calls in Redux?

A

Some of the popular middleware choices for handling asynchronous calls in Redux eco system are Redux Thunk, Redux Promise, Redux Saga.

278
Q

Do browsers understand JSX code?

A

No, browsers can’t understand JSX code. You need a transpiler to convert your JSX to regular Javascript that browsers can understand. The most widely used transpiler right now is Babel.

279
Q

What are the features of create react app?

A

Below are the list of some of the features provided by create react app.

  1. React, JSX, ES6, Typescript and Flow syntax support.
  2. Autoprefixed CSS
  3. CSS Reset/Normalize
  4. A live development server
  5. A fast interactive unit test runner with built-in support for coverage reporting
  6. A build script to bundle JS, CSS, and images for production, with hashes and sourcemaps
  7. An offline-first service worker and a web app manifest, meeting all the Progressive Web App criteria.
280
Q

What is Concurrent Rendering?

A

The Concurrent rendering makes React apps to be more responsive by rendering component trees without blocking the main UI thread. It allows React to interrupt a long-running render to handle a high-priority event. i.e, When you enabled concurrent Mode, React will keep an eye on other tasks that need to be done, and if there’s something with a higher priority it will pause what it is currently rendering and let the other task finish first. You can enable this in two ways,

// 1. Part of an app by wrapping with ConcurrentMode
<React.unstable_ConcurrentMode>
  <Something />
</React.unstable_ConcurrentMode>;

// 2. Whole app using createRoot
ReactDOM.unstable_createRoot(domNode).render(<App />);
281
Q

What is the difference between async mode and concurrent mode?

A

Both refers the same thing. Previously concurrent Mode being referred to as “Async Mode” by React team. The name has been changed to highlight React’s ability to perform work on different priority levels. So it avoids the confusion from other approaches to Async Rendering.

282
Q

Can I use javascript urls in react16.9?

A

Yes, you can use javascript: URLs but it will log a warning in the console. Because URLs starting with javascript: are dangerous by including unsanitized output in a tag like <a> and create a security hole.</a>

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.

283
Q

What is the difference between Imperative and Declarative in React?

A

Imagine a simple UI component, such as a “Like” button. When you tap it, it turns blue if it was previously grey, and grey if it was previously blue.

The imperative way of doing this would be:

if (user.likes()) {
  if (hasBlue()) {
    removeBlue();
    addGrey();
  } else {
    removeGrey();
    addBlue();
  }
}

Basically, you have to check what is currently on the screen and handle all the changes necessary to redraw it with the current state, including undoing the changes from the previous state. You can imagine how complex this could be in a real-world scenario.

In contrast, the declarative approach would be:

if (this.state.liked) {
  return <blueLike />;
} else {
  return <greyLike />;
}

Because the declarative approach separates concerns, this part of it only needs to handle how the UI should look in a sepecific state, and is therefore much simpler to understand.

284
Q

What are the benefits of using typescript with reactjs?

A

Below are some of the benefits of using typescript with Reactjs,

  1. It is possible to use latest JavaScript features
  2. Use of interfaces for complex type definitions
  3. IDEs such as VS Code was made for TypeScript
  4. Avoid bugs with the ease of readability and Validation
285
Q

What is state mutation and how to prevent it?

A

State mutation happens when you try to update the state of a component without actually using setState function. This can happen when you are trying to do some computations using a state variable and unknowingly save the result in the same state variable. This is the main reason why it is advised to return new instances of state variables from the reducers by using Object.assign({}, …) or spread syntax.

This can cause unknown issues in the UI as the value of the state variable got updated without telling React to check what all components were being affected from this update and it can cause UI bugs.

Ex:

class A extends React.component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false
    }
 }

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.

286
Q

What is the difference between useState and useRef hook?

A
  1. useState causes components to re-render after state updates whereas useRef doesn’t cause a component to re-render when the value or state changes. Essentially, useRef is like a “box” that can hold a mutable value in its (.current) property.
  2. useState allows us to update the state inside components. While useRef allows referencing DOM elements.