React Flashcards
- 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 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.
- 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.
JSX Code:
const App = () => { return <div>Hello world!</div> } Equivalent JS Code:
const App = () => { return React.createElement("div", null, "Hello world!"); };
JS is standard javascript, JSX is an HTML-like syntax that you can use with React to (theoretically) make it easier and more intuitive to create React components. As the docs say, the only purpose is to make it easier to create React components… there’s not much else there. Without JSX, creating large, nested HTML documents using JS syntax would be a large pain in the rear; JSX simply makes that process easier.
- What is the difference between Element and Component?
A React Component is a template. A blueprint. A global definition. This can be either a function or a class (with a render function).
A React Element is what gets returned from components. It’s an object that virtually describes the DOM nodes that a component represents. With a function component, this element is the object that the function returns. With a class component, the element is the object that the component’s render function returns. React elements are not what we see in the browser.
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 to create components in React?
When to use a Class Component over a Function Component?
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:
const FunctionalComponent = () => { return h1 Hello, world /h1 ; };
function FunctionalComponent() { return h1 Hello, world /h1 ; } Class Components: You can also use ES6 class to define a component. The above function component can be written as:
import React, { Component } from “react”;
class ClassComponent extends Component { render() { return h1 Hello, world /h1 ; } } without using destructuring
import React from “react”;
class ClassComponent extends React.Component { render() { return h1 Hello, world /h1 ; } }
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.
What are Pure Components? In class and in funcitonal.
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.
https://www.freecodecamp.org/news/react-shouldcomponentupdate-demystified-c5d323099ef6/
Reconciliation in the context of React means to make React’s virtual DOM tree consistent with the real DOM tree of your browser. This happens during (re-)rendering
To avoid unnecessary renders, thus reconciliation, we can use PureComponent (with class components) or React.memo() (with function components).
In PureComponent every time props or state changes, React performs a shallow compare between props and nextProps objects, and also between state and nextState objects.
React.memo() does the same as PureComponent but it does not check for changes in state, only in props.
Use pure components responsibly. The shallow comparison does not come for free. It’s an expensive computation and it’s better to avoid it if not necessary.
Don’t convert every component to pure, it could end up in worse performance.
Start instead by trying to convert a component to pure if it renders a lot of unnecessary times.
If you are not familiar with pure components, the advice is to only rely on them if you face some performance issues.
What is state in React?
What is State? The state is an instance of React Component Class can be defined as an object of a set of observable properties that control the behavior of the component. In other words, the State of a component is an object that holds some information that may change over the lifetime of the component.
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?
Below are some of the main differences between HTML and React event handling,
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 to bind methods or event handlers in JSX callbacks in class?
https://reactjs.org/docs/handling-events.html
You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.
read here
https://stackoverflow.com/questions/53215067/how-can-i-bind-function-with-hooks-in-react
There’s no need to bind functions/callbacks in functional components since there’s no this in functions. In classes, it was important to bind this because we want to ensure that the this in the callbacks referred to the component’s instance itself. However, doing .bind in the constructor has another useful property of creating the functions once during the entire lifecycle of the component and a new callback wasn’t created in every call of render(). To do only initialize the callback once using React hooks, you would use useCallback.
Classes class Foo extends Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); }
handleClick() {
console.log(‘Click happened’);
}
render() { return Click Me; } } Hooks function Foo() { const memoizedHandleClick = useCallback( () => { console.log('Click happened'); }, [], // Tells React to memoize regardless of arguments. ); return Click Me; }
- How to pass a parameter to an event handler or callback?
https://stackoverflow.com/questions/29810914/react-js-onclick-cant-pass-value-to-method
Easy Way
Use an arrow function:
return (
this.handleSort(column)}>{column}
);
This will create a new function that calls handleSort with the right params.
Better Way
Extract it into a sub-component. The problem with using an arrow function in the render call is it will create a new function every time, which ends up causing unneeded re-renders.
If you create a sub-component, you can pass handler and use props as the arguments, which will then re-render only when the props change (because the handler reference now never changes):
Sub-component
class TableHeader extends Component { handleClick = () => { this.props.onHeaderClick(this.props.value); }
render() {
return (
{this.props.column} ); } } Main component
{this.props.defaultColumns.map((column) => (
))}
Old Easy Way (ES5)
Use .bind to pass the parameter you want, this way you are binding the function with the Component context :
return (
{column}
);
What are synthetic events in React?
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.
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> }