React Questions Flashcards
Describe componentDidMount()
componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.
What problem does PureComponent solve?
By default, a plain React.Component has shouldComponentUpdate set to always return true. This is good because it means React errs on the side of always updating the component in case there’s any new data to show. However, it’s bad because it means React might trigger unnecessary re-renders. One way to deal with these extra re-renders is to change the shouldComponentUpdate function to check when your component needs to update (see my previous post for more information). Another way to stop extra re-renders is to use a PureComponent. Let’s build out the example from the previous performance post…
What is React?
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.
What are the major features of React?
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.
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 return as JavaScript function to the render function.
class App extends React.Component { render() { return( <div> <h1>{'Welcome to React world!'}</h1> </div> ) } }</h1>
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>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></div> Then JSX gets transpiled to a React.createElement() function tree:
const Button = ({ onLogin }) => React.createElement( 'div', { id: 'login-btn', onClick: onLogin }, 'Login' )
How to create components 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 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> } }
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.
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.
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 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.
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:
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
What is the difference between state and props?
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.
Why should we not update the state directly?
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.
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’))
What is the difference between HTML and React event handling?
i. In HTML, the event name should be in lowercase:
Whereas in React it follows camelCase convention:
ii. 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.’)
}