React Question

1. What is React?

React is an open-source front-end JavaScript library that 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 , a software engineer working for Facebook. React was first deployed on Facebook’s News Feed in 2011 and on Instagram in 2012.

2. What are the major features of React?

The major features of React are:

  • It uses VirtualDOM instead of 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.

3. What is JSX?

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 is returned as JavaScript function to the render function.

class App extends React.Component {
render() {
return(
<div>
<h1>{'Welcome to React world!'}</h1>
</div>
)
}
}

4. What is the difference between Element and Component?

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 id='login-btn'>Login</div>

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 = ({ onLogin }) =>
<div id={'login-btn'} onClick={onLogin}>Login</div>

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

const Button = ({ onLogin }) => React.createElement(
'div',
{ id: 'login-btn', onClick: onLogin },
'Login'
)

5. When to use a Class Component over a Function Component?

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. *So, it is always recommended to use Function components, unless you need a React functionality whose Function component equivalent is not present yet, like Error Boundaries *

6. What are Pure Components?

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.

7. What is state in React?

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

8. What are props in React?

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:

  1. Pass custom data to your component.
  2. Trigger state changes.
  3. Use via this.props.reactProp inside component's render() method.

For example, let us create an element with reactProp property:

<Element reactProp={'1'} />

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

Example: Props in Class Based Component

import React from 'react'
import ReactDOM from 'react-dom'
class ChildComponent extends React.Component {
render() {
return (
<div>
<p>{this.props.name}</p>
<p>{this.props.age}</p>
</div>
)
}
}
class ParentComponent extends React.Component {
render() {
return (
<div>
<ChildComponent name='John' age='30' />
<ChildComponent name='Mary' age='25' />
</div>
)
}
}

Example: Props in Functional Component

import React from 'react'
import ReactDOM from 'react-dom'
const ChildComponent = (props) => {
return (
<div>
<p>{props.name}</p>
<p>{props.age}</p>
</div>
)
}
const ParentComponent = () => {
return (
<div>
<ChildComponent name='John' age='30' />
<ChildComponent name='Mary' age='25' />
</div>
)
}

9. What is the difference between state and props?

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

10. Why should we not update the state directly?

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' })
  1. Note: You can directly assign to the state object either in constructor or using latest javascript’s class field declaration syntax.

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

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'))

12. What is the difference between HTML and React event handling?

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

  1. In HTML, the event name usually represents in lowercase as a 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.')
}
  1. 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)

13. How to bind methods or event handlers in JSX callbacks?

There are 3 possible ways to achieve this:

  1. 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 Foo extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('Click happened');
}
render() {
return <button onClick={this.handleClick}>Click Me</button>;
}
}

2. 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)
}
<button onClick={this.handleClick}>
{'Click me'}
</button>

3. Arrow functions in callbacks: You can use arrow functions directly in the callbacks.

handleClick() {
console.log('Click happened');
}
render() {
return <button onClick={() => this.handleClick()}>Click Me</button>;
}
  1. 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.

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

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

15. What are synthetic events in React?

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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kang Wang

Process Mining, Data Scientist, Research Software Engineer, Climbing, ERP.