What is React?
React(aka React.js or ReactJS) is an open-source front-end JavaScript library that is used for building composable user interfaces, especially for single-page applications. It is used for handling view layer for web and mobile apps based on components in a declarative approach.
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 is the history behind React evolution?
The history of ReactJS started in 2010 with the creation of XHP. XHP is a PHP extension which improved the syntax of the language such that XML document fragments become valid PHP expressions and the primary purpose was used to create custom and reusable HTML elements.
The main principle of this extension was to make front-end code easier to understand and to help avoid cross-site scripting attacks. The project was successful to prevent the malicious content submitted by the scrubbing user.
But there was a different problem with XHP in which dynamic web applications require many roundtrips to the server, and XHP did not solve this problem. Also, the whole UI was re-rendered for small change in the application. Later, the initial prototype of React is created with the name FaxJ by Jordan inspired from XHP. Finally after sometime React has been introduced as a new library into JavaScript world.
Note: JSX comes from the idea of XHP
What are the major features of React?
The major features of React are:
- Uses JSX syntax, a syntax extension of JS that allows developers to write HTML in their JS code.
- It uses Virtual DOM instead of Real DOM considering that Real DOM manipulations are expensive.
- Supports server-side rendering which is useful for Search Engine Optimizations(SEO).
- Follows Unidirectional or one-way data flow or data binding.
- Uses reusable/composable UI components to develop the view.
What is JSX?
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!’
);
}
·
Note: JSX is stricter than HTML
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 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 to create components in React?
Components are the building blocks of creating User Interfaces(UI) in React. There are two possible ways to create a component.
1. 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:
2. function Greeting({ message }) {
3. 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>;
}
}
When to use a Class Component over a Function Component?
After the addition of Hooks(i.e. React 16.8 onwards) it is always recommended to use Function components over Class components in React. Because you could use state, lifecycle methods and other features that were only available in class component present in function component too.
But even there are two reasons to use Class components over Function components.
If you need a React functionality whose Function component equivalent is not present yet, like Error Boundaries.
In older versions, If the component needs state or lifecycle methods then you need to use class component.
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.
“use client”;
import { ErrorBoundary } from “react-error-boundary”;
<ErrorBoundary fallback={<div>Something went wrong</div>}>
<ExampleApplication />
</ErrorBoundary>
What are Pure Components?
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.
The syntactic representation of memoized components looks like below,
const MemoizedComponent = memo(SomeComponent, arePropsEqual?);
Below is the example of how child component(i.e., EmployeeProfile) prevents re-renders for the same props passed by parent component(i.e.,EmployeeRegForm).
import { memo, useState } from ‘react’;
const EmployeeProfile = memo(function EmployeeProfile({ name, email }) {
return (<>
<p>Name:{name}</p>
<p>Email: {email}</p>
</>);
});
export default function EmployeeRegForm() {
const [name, setName] = useState(”);
const [email, setEmail] = useState(”);
return (
<>
<label>
Name: <input value={name} onChange={e => setName(e.target.value)} />
</label>
<label>
Email: <input value={email} onChange={e => setEmail(e.target.value)} />
</label>
<hr/>
<EmployeeProfile name={name}/>
</>
);
}
· In the above code, the email prop has not been passed to child component. So there won’t be any re-renders for email prop change.
In class components, the components extending React.PureComponent instead of React.Component become the pure components. When props or state changes, PureComponent will do a shallow comparison on both props and state by invoking shouldComponentUpdate() lifecycle method.
Note: React.memo() is a higher-order component.
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. The important point is whenever the state object changes, the component re-renders. It is always recommended to make our state as simple as possible and minimize the number of stateful components.
Let’s take an example of User component with message state. Here, useState hook has been used to add state to the User component and it returns an array with current state and function to update it.
import React, { useState } from “react”;
function User() {
const [message, setMessage] = useState(“Welcome to React world”);
return (
<div>
<h1>{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.
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 similar to HTML-tag attributes. Here, the data is passed down from a parent component to a child component.
The primary purpose of props in React is to provide following component functionality:
Pass custom data to your component.
Trigger state changes.
Use via this.props.reactProp inside component’s render() method.
For example, let us create an element with reactProp property:
<Element reactProp={“1”} />
This reactProp (or whatever you came up with) attribute 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
For example, the usage of props in function component looks like below:
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>
);
};
The properties from props object can be accessed directly using destructing feature from ES6 (ECMAScript 2015). The above child component can be simplified like below.
const ChildComponent = ({name, age}) => {
return (
<div>
<p>{name}</p>
<p>{age}</p>
</div>
);
};
What is the difference between state and props?
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.
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” });
· 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?
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()”></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 to bind methods or event handlers in JSX callbacks?
There are 3 possible ways to achieve this in class components:
1. Binding in Constructor: In JavaScript classes, the methods are not bound by default. The same rule applies for React event handlers defined as class methods. Normally we bind them in constructor.
2. class User extends Component {
3. constructor(props) {
4. super(props);
5. this.handleClick = this.handleClick.bind(this);
6. }
7. handleClick() {
8. console.log(“SingOut triggered”);
9. }
10. render() {
11. return <button onClick={this.handleClick}>SingOut</button>;
12. }
}
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. The Create React App eanables this syntax by default.
handleClick = () => {
console.log(“SingOut triggered”, this);
};
<button onClick={this.handleClick}>SingOut</button>
Arrow functions in callbacks: It is possible to use arrow functions directly in the callbacks.
handleClick() {
console.log(‘SingOut triggered’);
}
render() {
return <button onClick={() => this.handleClick()}>SignOut</button>;
}
· 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 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);
};
What are synthetic events in React?
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} />
}
What are inline conditional expressions?
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>
);
}
What is “key” prop and what is the benefit of using it in arrays of elements?
A key is a special attribute you should include when mapping over arrays to render data. Key prop helps React identify which items have changed, are added, or are removed.
Keys should be unique among its siblings. Most often we use ID from our data as key:
const todoItems = todos.map((todo) => <li key={todo.id}>{todo.text}</li>);
When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort:
const todoItems = todos.map((todo, index) => (
<li key={index}>{todo.text}</li>
));
· Note:
Using indexes for keys is not recommended if the order of items may change. This can negatively impact performance and may cause issues with component state.
If you extract list item as separate component then apply keys on list component instead of li tag.
There will be a warning message in the console if the key prop is not present on list items.
The key attribute accepts either string or number and internally convert it as string type.
What is the use of refs?
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 to create refs?
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.
2. class MyComponent extends React.Component {
3. constructor(props) {
4. super(props);
5. this.myRef = React.createRef();
6. }
7. render() {
8. return <div ref={this.myRef} />;
9. }
}
You can also use ref callbacks approach regardless of React version. For example, the search bar component’s input element is 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 (
<input
value={this.state.term}
onChange={this.onInputChange.bind(this)}
ref={this.setInputSearchRef}
/>
);
}
}
· 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.
What are forward refs?
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>;
Which is preferred option with in callback refs and findDOMNode()?
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 />;
}
}
The recommended approach is:
class MyComponent extends Component {
constructor(props) {
super(props);
this.node = createRef();
}
componentDidMount() {
this.node.current.scrollIntoView();
}
render() {
return <div ref={this.node} />;
}
}
Why are String Refs legacy?
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.
1. 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.
2. 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.
3. 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.
4. It doesn’t work as most people would expect with the “render callback” pattern (e.g. )
5. class MyComponent extends Component {
6. renderRow = (index) => {
7. // This won’t work. Ref will get attached to DataTable rather than MyComponent:
8. return <input ref={“input-” + index} />;
9.
10. // This would work though! Callback refs are awesome.
11. return <input ref={(input) => (this[“input-” + index] = input)} />;
12. };
13.
14. render() {
15. return (
16. <DataTable data={this.props.data} renderRow={this.renderRow} />
17. );
18. }
}
What is Virtual DOM?
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 Virtual DOM works?
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.
What is the difference between Shadow DOM and Virtual DOM?
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.
What is React Fiber?
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.
What is the main goal of React Fiber?
The goal of React Fiber is to increase its suitability for areas like animation, layout, and gestures. Its headline feature is incremental rendering: the ability to split rendering work into chunks and spread it out over multiple frames.
from documentation
Its main goals are:
Ability to split interruptible work in chunks.
Ability to prioritize, rebase and reuse work in progress.
Ability to yield back and forth between parents and children to support layout in React.
Ability to return multiple elements from render().
Better support for error boundaries.
What are controlled components?
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()})
}
What are uncontrolled components?
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.
What is the difference between createElement and cloneElement?
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.
What is Lifting State Up in React?
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.
What are the different phases of component lifecycle?
The component lifecycle has three distinct lifecycle phases:
1. Mounting: The component is ready to mount in the browser DOM. This phase covers initialization from constructor(), getDerivedStateFromProps(), render(), and componentDidMount() lifecycle methods.
2. Updating: In this phase, the component gets 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.
3. Unmounting: In this last phase, the component is not needed and gets 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
1. Render The component will render without any side effects. This applies to Pure components and in this phase, React can pause, abort, or restart the render.
2. 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().
3. Commit React works with the DOM and executes the final lifecycles respectively componentDidMount() for mounting, componentDidUpdate() for updating, and componentWillUnmount() for unmounting.
What are the lifecycle methods of React?
Before React 16.3
componentWillMount: Executed before rendering and is used for App level configuration in your root component.
componentDidMount: Executed after first rendering and here all AJAX requests, DOM or state updates, and set up event listeners should occur.
componentWillReceiveProps: Executed when particular prop updates to trigger state transitions.
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.
componentWillUpdate: Executed before re-rendering the component when there are props & state changes confirmed by shouldComponentUpdate() which returns true.
componentDidUpdate: Mostly it is used to update the DOM in response to prop or state changes.
componentWillUnmount: It will be used to cancel any outgoing network requests, or remove all event listeners associated with the component.
React 16.3+
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.
componentDidMount: Executed after first rendering and where 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 the state or props are updated, you can return a false value. It is a great place to improve performance as it allows you to prevent a re-render if component receives a 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.
What are Higher-Order Components?
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 to create props proxy for HOC component?
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} />;
}
};
}
What is context?
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);
What is children prop?
Children is a prop (this.props.children) that allows you to pass components as data to other components, just like any other prop you use. Component tree put between component’s opening and closing tag will be passed to that component as children prop.
There are several 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(
<MyDiv>
<span>{“Hello”}</span>
<span>{“World”}</span>
</MyDiv>,
node
);
How to write comments in React?
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>
What is the purpose of using super constructor with props argument?
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.
What is reconciliation?
· 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 to set state with a dynamic key name?
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 })
}
What would be the common mistake of function being called every time the component renders?
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>
}
Is lazy function supports named exports?
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”));
Why React uses className over class attribute?
The attribute 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 className={‘menu navigation-menu’}>{‘Menu’}</span>
}
What are fragments?
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>
);
}
Ususally 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>
</>
);