Core React Flashcards

1
Q

What is React?

A

React is an open-source frontend JavaScript library which is used for building user interfaces especially for single page applications. It is used for handling view layer for web and mobile apps. React was created by Jordan Walke, a software engineer working for Facebook. React was first deployed on Facebook’s News Feed in 2011 and on Instagram in 2012.

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

What are the major features of React?

A

The major features of React are:

  • It uses VirtualDOM instead RealDOM considering that
  • RealDOM manipulations are expensive.
  • Supports server-side rendering.
  • Follows Unidirectional 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

What is JSX?

A

JSX is a XML-like syntax extension to ECMAScript (the acronym stands for JavaScript XML). Basically it just provides syntactic sugar for the React.createElement() function, giving us expressiveness of JavaScript along with HTML like template syntax.

In the example below text inside <h1> tag return as JavaScript function to the render function.

class App extends React.Component {
  render() {
    return(
      <div>
        <h1>{'Welcome to React world!'}</h1>
      </div>
    )
  }
}</h1>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
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 is never mutated.

The object representation of React Element would be as follows:

const element = React.createElement(
  'div',
  {id: 'login-btn'},
  'Login'
)
The above React.createElement() function returns an object:
{
  type: 'div',
  props: {
    children: 'Login',
    id: 'login-btn'
  }
}

And finally it renders to the DOM using ReactDOM.render():

<div>Login</div>

Whereas a component can be declared in several different ways. It can be a class with a render() method. Alternatively, in simple cases, 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 = ({ onLogin }) =>
  <div>Login</div>
Then JSX gets transpiled to a React.createElement() function tree:
const Button = ({ onLogin }) => React.createElement(
  'div',
  { id: 'login-btn', onClick: onLogin },
  'Login'
)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to create components in React?

A

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 first parameter and return React elements:

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:
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
6
Q

When to use a Class component over a Functional component?

A

If the component needs state or lifecycle methods then use class component otherwise use function component. However, from React 16.8 with the addition of Hooks, you could use state , lifecycle methods and other features that were only available in class component right in your function component.

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

What are pure components?

A

React.PureComponent is exactly the same as React.Component except that it handles the shouldComponentUpdate() method for you. When props or state changes, PureComponent will do a shallow comparison on both props and state. Component on the other hand won’t compare current props and state to next out of the box. Thus, the component will re-render by default whenever shouldComponentUpdate is called.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
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. We should always try to make our state as simple as possible and minimize the number of stateful components. Let’s create an user component with message state,

class User extends React.Component {
  constructor(props) {
    super(props)
this.state = {
  message: 'Welcome to React world'
}   }
  render() {
    return (
      <div>
        <h1>{this.state.message}</h1>
      </div>
    )
  }
}
state

State is similar to props, but it is private and fully controlled by the component. i.e, It is not accessible to any component other than the one that owns and sets it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
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 using a naming convention similar to HTML-tag attributes. They are data passed down from a parent component to a child component.

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

Pass custom data to your component.
Trigger state changes.
Use via this.props.reactProp inside component’s render() method.
For example, let us create an element with reactProp property:

This reactProp (or whatever you came up with) name then becomes a property attached to React’s native props object which originally already exists on all components created using React library.

props.reactProp

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

What is the difference between state and props?

A

Both props and state are plain JavaScript objects. While both of them hold information that influences the output of render, they are different in their functionality with respect to component. Props get passed to the component similar to function parameters whereas state is managed within the component similar to variables declared within a function.

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

Why should we not update the state directly?

A

If you try to update 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
12
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
13
Q

What is the difference between HTML and React event handling?

A

In HTML, the event name should be in lowercase:

Whereas in React it follows camelCase convention:

In HTML, you can return false to prevent default behavior:
<a></a>
Whereas in React you must call preventDefault() explicitly:

function handleClick(event) {
  event.preventDefault()
  console.log('The link was clicked.')
}
In HTML, you need to invoke the function by appending () Whereas in react you should not append () with the function name. (refer "activateLasers" function in the first point for example)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How to bind methods or event handlers in JSX callbacks?

A

There are 3 possible ways to achieve this:

Binding in Constructor: In JavaScript classes, the methods are not bound by default. The same thing applies for React event handlers defined as class methods. Normally we bind them in constructor.
class Component extends React.Componenet {
  constructor(props) {
    super(props)
    this.handleClick = this.handleClick.bind(this)
  }
  handleClick() {
    // ...
  }
}
Public class fields syntax: If you don't like to use bind approach then public class fields syntax can be used to correctly bind callbacks.
handleClick = () => {
  console.log('this is:', this)
}

{‘Click me’}

Arrow functions in callbacks: You can use arrow functions directly in the callbacks.
this.handleClick(event)}>
{‘Click me’}

Note: If the callback is passed as prop to child components, those components might do an extra re-rendering. In those cases, it is preferred to go with .bind() or public class fields syntax approach considering performance.

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

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:

this.handleClick(id)} />
This is an equivalent to calling .bind:

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

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

What are synthetic events in React?

A

SyntheticEvent is a cross-browser wrapper around the browser’s native event. It’s API is same as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.

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

What is 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
18
Q

What are “key” props and what is the benefit of using them in arrays of elements?

A

A key is a special string attribute you should include when creating arrays of elements. Keys help React identify which items have changed, are added, or are removed.

Most often we use IDs from our data as keys:

const todoItems = todos.map((todo) =>
  <li>
    {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>
    {todo.text}
  </li>
)
Note:

Using indexes for keys is not recommended if the order of items may change. This can negatively impact performance and may cause issues with component state.
If you extract list item as separate component then apply keys on list component instead of li tag.
There will be a warning message in the console if the key prop is not present on list items.

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

How to create refs?

A

There are two approaches

  1. This is a recently added approach. Refs are created using React.createRef() method and attached to React elements via the ref attribute. In order to use refs throughout the component, just assign the ref to the instance property within constructor.
class MyComponent extends React.Component {
  constructor(props) {
    super(props)
    this.myRef = React.createRef()
  }
  render() {
    return <div></div>
  }
}
  1. You can also use ref callbacks approach regardless of React version. For example, the search bar component’s input element accessed as follows,
class SearchBar extends Component {
   constructor(props) {
      super(props);
      this.txtSearch = null;
      this.state = { term: '' };
      this.setInputSearchRef = e => {
         this.txtSearch = e;
      }
   }
   onInputChange(event) {
      this.setState({ term: this.txtSearch.value });
   }
   render() {
      return (
  );    } }

You can also use refs in function components using closures. Note: You can also use inline ref callbacks even though it is not a recommended approach

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

{props.children}

));

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

Which is preferred option with in callback refs and findDOMNode()?

A

It is preferred to use callback refs over findDOMNode() API. Because findDOMNode() prevents certain improvements in React in the future.

The legacy approach of using findDOMNode:

class MyComponent extends Component {
  componentDidMount() {
    findDOMNode(this).scrollIntoView()
  }
  render() {
    return <div></div>
  }
}
The recommended approach is:
class MyComponent extends Component {
  constructor(props){
    super(props);
    this.node = createRef();
  }
  componentDidMount() {
    this.node.current.scrollIntoView();
  }

render() {
return <div></div>
}
}

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

Why are String Refs legacy?

A

If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like ref={‘textInput’}, and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have below issues, and are considered legacy. String refs were removed in React v16.

They force React to keep track of currently executing component. This is problematic because it makes react module stateful, and thus causes weird errors when react module is duplicated in the bundle.
They are not composable — if a library puts a ref on the passed child, the user can't put another ref on it. Callback refs are perfectly composable.
They don't work with static analysis like Flow. Flow can't guess the magic that framework does to make the string ref appear on this.refs, as well as its type (which could be different). Callback refs are friendlier to static analysis.
It doesn't work as most people would expect with the "render callback" pattern (e.g. )
class MyComponent extends Component {
  renderRow = (index) => {
    // This won't work. Ref will get attached to DataTable rather than MyComponent:
    return ;
    // This would work though! Callback refs are awesome.
    return  this['input-' + index] = input} />;
  }

render() {
return
}
}

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

What is Virtual DOM?

A

The Virtual DOM (VDOM) is an in-memory representation of Real DOM. The representation of a UI is kept in memory and synced with the “real” DOM. It’s a step that happens between the render function being called and the displaying of elements on the screen. This entire process is called reconciliation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
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. vdom
  2. Then the difference between the previous DOM representation and the new one is calculated. vdom2
  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
26
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
27
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
28
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.

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

      {'Name:'}

);   } } In most cases, it's recommend to use controlled components to implement forms.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
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
32
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
33
Q

What are the phases of component lifecycle?

A

The component lifecycle has three distinct lifecycle phases:

Mounting: The component is ready to mount in the browser DOM. This phase covers initialization from constructor(), getDerivedStateFromProps(), render(), and componentDidMount() lifecycle methods.

Updating: In this phase, the component get updated in two ways, sending the new props and updating the state either from setState() or forceUpdate(). This phase covers getDerivedStateFromProps(), shouldComponentUpdate(), render(), getSnapshotBeforeUpdate() and componentDidUpdate() lifecycle methods.

Unmounting: In this last phase, the component is not needed and get unmounted from the browser DOM. This phase includes componentWillUnmount() lifecycle method.

It’s worth mentioning that React internally has a concept of phases when applying changes to the DOM. They are separated as follows

Render The component will render without any side-effects. This applies for Pure components and in this phase, React can pause, abort, or restart the render.

Pre-commit Before the component actually applies the changes to the DOM, there is a moment that allows React to read from the DOM through the getSnapshotBeforeUpdate().

Commit React works with the DOM and executes the final lifecycles respectively componentDidMount() for mounting, componentDidUpdate() for updating, and componentWillUnmount() for unmounting.

https://github.com/sudheerj/reactjs-interview-questions/raw/master/images/phases.png

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

What are the lifecycle methods of React?

A

React 16.3+

getDerivedStateFromProps: Invoked right before calling render() and is invoked on every render. This exists for rare use cases where you need derived state. Worth reading if you need derived state.
componentDidMount: Executed after first rendering and here all AJAX requests, DOM or state updates, and set up event listeners should occur.
shouldComponentUpdate: Determines if the component will be updated or not. By default it returns true. If you are sure that the component doesn’t need to render after 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.
getSnapshotBeforeUpdate: Executed right before rendered output is committed to the DOM. Any value returned by this will be passed into componentDidUpdate(). This is useful to capture information from the DOM i.e. scroll position.
componentDidUpdate: Mostly it is used to update the DOM in response to prop or state changes. This will not fire if shouldComponentUpdate() returns false.
componentWillUnmount It will be used to cancel any outgoing network requests, or remove all event listeners associated with the component.

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

What are higher order components?

A

A higher-order component (HOC) is a function that takes a component and returns a new component. Basically, it’s a pattern that is derived from React’s compositional nature.

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

const EnhancedComponent = higherOrderComponent(WrappedComponent)
HOC can be used for many use cases:

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

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

What is 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 user, locale preference, UI theme 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
37
Q

What is children prop?

A

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

There are a number of methods available in the React API to work with this prop. These include React.Children.map, React.Children.forEach, React.Children.count, React.Children.only, React.Children.toArray. A simple usage of children prop looks as below,

const MyDiv = React.createClass({
  render: function() {
    return <div>{this.props.children}</div>
  }
})

ReactDOM.render(

    <span>{'Hello'}</span>
    <span>{'World'}</span>
  ,
  node
)
38
Q

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

A

A child class constructor cannot make use of this reference until super() method has been called. The same applies for ES6 sub-classes as well. The main reason of 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.
39
Q

What is reconciliation?

A

When a component’s props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one. When they are not equal, React will update the DOM. This process is called reconciliation.

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

41
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 {'Click Me'}
}
Instead, pass the function itself without parenthesis:
render() {
  // Correct: handleClick is passed as a reference!
  return {'Click Me'}
}
42
Q

Why React uses className over class attribute?

A

class is a keyword in JavaScript, and JSX is an extension of JavaScript. That’s the principal reason why React uses className instead of class. Pass a string as the className prop.

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

43
Q

What are fragments?

A

It’s common pattern in React which is used for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.

render() {
return (

)
}
There is also a shorter syntax, but it’s not supported in many tools:

render() {
return (
<>

>   ) }
44
Q

Why are fragments better than container divs?

A
  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.
45
Q

What are stateless components?

A

If the behaviour 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.

46
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 always class components and have a state that gets initialized in the constructor.

class App extends Component {
  constructor(props) {
    super(props)
    this.state = { count: 0 }
  }
  render() {
    // ...
  }
}

React 16.8 Update: Hooks let you use state and other React features without writing classes.

The Equivalent Functional Component

import React, {useState} from ‘react’;

const App = (props) => {
  const [count, setCount] = useState(0);
  return (
    // JSX
  )
}
47
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 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
We can define propTypes for User component as below:

import React from ‘react’
import PropTypes from ‘prop-types’

class User extends React.Component {
  static propTypes = {
    name: PropTypes.string.isRequired,
    age: PropTypes.number.isRequired
  }

render() {
return (
<>
<h1>{Welcome, ${this.props.name}}</h1>
<h2>{Age, ${this.props.age}}</h2>
>
)
}
}
Note: In React v15.5 PropTypes were moved from React.PropTypes to prop-types library.

48
Q

What are the advantages of React?

A
  1. Increases the application’s performance with Virtual DOM.
  2. JSX makes code easy to read and write.
  3. It renders both on client and server side (SSR).
  4. Easy to integrate with frameworks (Angular, Backbone) since it is only a view library.
  5. Easy to write unit and integration tests with tools such as Jest.
49
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.
50
Q

What is the use of the 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:

render()
hydrate()
unmountComponentAtNode()
findDOMNode()
createPortal()
51
Q

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

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.

52
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(‘My Page’)
res.write(‘<div>’)
res.write(renderToString())
res.write(‘</div>’)
res.end()
})

53
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 · Second' }
}
function MyComponent() {
  return <div></div>
}
54
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="">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).
55
Q

How are events different in React?

A

Handling events in React elements has some syntactic differences:

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

56
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) =>

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

)}

57
Q

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

A

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]
      })
    })
}
58
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 &amp;&amp;
      <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>
)
59
Q

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

A

When we spread props we run into the risk of adding unknown HTML attributes, which is a bad practice. Instead we can use prop destructuring with …rest operator, so it will add only required props. For example,

const ComponentA = () =>

const ComponentB = ({ isDisplay, ...domProps }) =>
  <div>{'ComponentB'}</div>
60
Q

How do you memoize a component?

A

There are memoize libraries available which can be used on function components. For example moize library can memoize the component in another component.

import moize from 'moize'
import Component from './components/Component' // this module exports a non-memoized component

const MemoizedFoo = moize.react(Component)

const Consumer = () => {
  <div>
    {'I will memoize the following entry:'}

</div>
}

61
Q

How do you equip 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()
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.

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

63
Q

What is Create React App and its benefits?

A

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

Let’s create Todo App using CRA:

# Installation
$ npm install -g create-react-app
# Create new project
$ create-react-app todo-app
$ cd todo-app
# Build, test and run
$ npm run build
$ npm run test
$ npm start
It includes everything we need to build a React app:

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

64
Q

What are 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.

constructor()
static getDerivedStateFromProps()
render()
componentDidMount()

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

66
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().
67
Q

Do Hooks replace render props and higher order components?

A

Both render props and higher-order components render only a single child but in most of the cases Hooks are a simpler way to serve this by reducing nesting in your tree.

68
Q

What is the recommended way for naming components?

A

It is recommended to name the component by reference instead of using displayName.

Using displayName for naming component:

export default React.createClass({
  displayName: 'TodoApp',
  // ...
})
The recommended approach:
export default class TodoApp extends React.Component {
  // ...
}
69
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()
70
Q

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

A

The reason behind for this is that setState() is an asynchronous operation. React batches state changes for performance reasons, so the state may not change immediately after setState() is called. That means you should not rely on the current state when calling setState() since you can’t be sure what that state will be. The solution is to pass a function to setState(), with the previous state as an argument. By doing this you can avoid issues with the user getting the old state value on access due to the asynchronous nature of setState().

Let’s say the initial count value is zero. After three consecutive increment operations, the value is going to be incremented only by one.

// assuming this.state.count === 0
this.setState({ count: this.state.count + 1 })
this.setState({ count: this.state.count + 1 })
this.setState({ count: this.state.count + 1 })
// this.state.count === 1, not 3
If we pass a function to setState(), the count gets incremented correctly.

this.setState((prevState, props) => ({
count: prevState.count + props.increment
}))
// this.state.count === 3 as expected

71
Q

Why should component names start with a 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 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></div>
  }
}

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

import MyComponent from ‘./MyComponent’

72
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.
73
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.
74
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:

{items.map(item => )}

You can’t iterate using for loop:

for (let i = 0; i < items.length; i++) {

}

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.

75
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></img>
But you can put any JS expression inside curly braces as the entire attribute value. So the below expression works:

<img></img>
Using template strings will also work:

<img></img>

76
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>
Instead you need to move curly braces outside (don't forget to include spaces between class names):

<div>
Template strings will also work:

<div></div></div>

</div>

77
Q

What is the difference between React and ReactDOM and why are they separate?

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

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.

78
Q

How to use React label element?

A

If you try to render a 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.

{‘User’}

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

{‘User’}

79
Q

How to combine multiple inline style objects?

A

You can use spread operator in regular React:

{‘Submit’}
If you’re using React Native then you can use the array notation:

{‘Submit’}

80
Q

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

A

You can listen to the resize event in componentDidMount() and then update the dimensions (width and height). You should remove the listener in componentWillUnmount() method.

class WindowDimensions extends React.Component {
  constructor(props){
    super(props);
    this.updateDimensions = this.updateDimensions.bind(this);
  }

componentWillMount() {
this.updateDimensions()
}

componentDidMount() {
window.addEventListener(‘resize’, this.updateDimensions)
}

componentWillUnmount() {
window.removeEventListener(‘resize’, this.updateDimensions)
}

updateDimensions() {
this.setState({width: window.innerWidth, height: window.innerHeight})
}

render() {
return <span>{this.state.width} x {this.state.height}</span>
}
}

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

82
Q

How to listen to state changes?

A

The following lifecycle methods will be called when state changes. You can compare provided state and props values with current state and props to determine if something meaningful changed.

componentWillUpdate(object nextProps, object nextState)
componentDidUpdate(object prevProps, object prevState)

83
Q

What are the possible ways of updating objects in state?

A
  1. 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 })
  1. Calling setState() with a function:

this.setState(prevState => ({
user: {
…prevState.user,
age: 42
}
}))

84
Q

Why function is preferred over object for setState()?

A

React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

This counter example will fail to update as expected:

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
})
The preferred approach is to call setState() with function rather than object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument.
// Correct
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}))
85
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

86
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 (
    //...
    )
  }
}
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.
87
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.

88
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:

this.inputElement = input} />
Apply click event in your event handler:

this.inputElement.click()

89
Q

Is it possible to use async/await in plain React?

A

If you want to use async/await in React, you will need Babel and transform-async-to-generator plugin. React Native ships with Babel and a set of transforms.

90
Q

What are 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
91
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’