React I Flashcards
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.
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.
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.
Then JSX gets transpiled to a React.createElement() function tree.
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.
Function Components: This is the simplest way to create a component. Those are pure JavaScript functions that accept props object as the one and only one parameter and return React elements to render the output: 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 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.
Use Function Components:
If you don’t need state or lifecycle methods, and your component is purely presentational.
For simplicity, readability, and modern code practices, especially with the use of React Hooks for state and side effects.
Use Class Components:
If you need to manage state or use lifecycle methods.
In scenarios where backward compatibility or integration with older code is necessary.
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.
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.
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.
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.
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.
The state entity is managed by the component itself and can be updated using the setter(setState() for class components) function. Unlike props, state can be modified by the component and is used to manage the internal state of the component. i.e, state acts as a component’s memory. Moreover, changes in the state trigger a re-render of the component and its children. The components cannot become reusable with the usage of state alone.
On the otherhand, 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 own component itself. i.e, props acts as arguments for a function. Also, props can be used to configure the behavior of a component and to pass data between components. The components become reusable with the usage of props.
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 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></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)
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.
function BookStore() {
function handleTitleChange(e) {
console.log(“The new title is:”, e.target.value);
// ‘e’ represents synthetic event
const nativeEvent = e.nativeEvent;
console.log(nativeEvent);
e.stopPropagation();
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. Don't generate the key on the fly something like key={Math.random()}. Because the keys will never match up between re-renders and DOM created everytime.
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.
The Virtual DOM works in three simple steps.
** Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representati**on.
Then the difference between the previous DOM representation and the new one is calculated.
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.
Reconciliation is the process React uses to efficiently update the DOM when the state or props of a component change. Instead of re-rendering everything, React compares the new virtual DOM with the previous one and updates only the changed parts.
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. That means, the displayed data is always in sync with the state of the component.
The controlled components will be implemented using the below steps,
Initialize the state using useState hooks in function components or inside constructor for class components. Set the value of the form element to the respective state variable. Create an event handler to handle the user input changes through useState updater function or setState from class component. Attach the above event handler to form elements change or click events
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.
The uncontrolled components will be implemented using the below steps,
Create a ref using useRef react hook in function component or React.createRef() in class based component. Attach this ref to the form element. The form element value can be accessed directly through ref in event handlers or componentDidMount for class components
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 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.
{title}
{description}
{date}
{story.title}
{story.description}
{story.date}