React

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

What are the different phases of component lifecycle?

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 get 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 n this last phase, the component is not needed and get unmounted from the browser DOM. This phase includes componentWillUnmount() lifecycle method.

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

1. using an arrow functio in jsx 2. using bind which takes 'this' and arguments and returns a new function (unfired) 3. or this handleClick = id => () =>

Difference between '==' and '==='

== is the abstract equality operator === is the strict equality operator

What do you understand by Virtual DOM? Explain its working.

A virtual DOM is a lightweight JavaScript object which originally is just the copy of the real DOM. It is a node tree that lists the elements, their attributes and content as Objects and their properties. React's render function creates a node tree out of the React components. It then updates this tree in response to the mutations in the data model which is caused by various actions done by the user or by the system. This 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 are closures

Closures are functions that have access to the outer (enclosing) function's variables—scope chain even after the outer function has returned.

What does IIFE mean?

Immediately Invoked Function Expression example const win = (() => true)() // win is true

What happens when a component is mounted?

It is inserted into the tree

What's the difference between host objects and native objects

Native: think vs code builtins. Math, RegExp, Object, Function, String Host: think browser window, XMLHTTPRequest

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.

What are the limitations of React?

React is just a library, not a full-blown framework Its library is very large and takes time to understand It can be little difficult for the novice programmers to understand Coding gets complex as it uses inline templating and JSX

Difference between Real DOM and Virtual DOM

Real DOM 1. updates slow 2. Can directly update HTML 3. Creates a new DOM if element updates 4. DOM Manipulation is very expensive 5. Too much of memory wastage Virtual DOM 1. updates faster 2. Can't directly update HTML 3. Updates the JSX if Element updates 4. DOM manipulation is very easy 5. No memory wastage

render()

Render us the method that actual outputs HTML to the DOM and it returns a single element that represents the component during the rendering process. This element could be native DOM component like (</p>,</div>...) or a component that been defined by a User. This render() will be recalled after any change to the component's props or state.

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

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.

What is the difference between .map and .forEach

The main difference between .forEach and .map() is that .map() returns a new array. If you need the result, but do not wish to mutate the original array, .map() is the clear choice. If you simply need to iterate over an array, forEach is a fine choice.

Explain the same-origin policy with regards to JavaScript.

The same-origin policy prevents JavaScript from making requests across domain boundaries. An origin is defined as a combination of URI scheme, hostname, and port number. This policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page's Document Object Model.

What are Pure Functions in JS?

They are functions that do not contain references to data/variables in their outer scope, thus we can expect that inputs will always return the same outputs. Also, there is no data modifications to variables that do not belong to the function

What is the difference between HTML and React event handling?

lowercase vs camelCase In HTML, you can return false to prevent default behavior: Whereas in React you must call preventDefault() explicitly: 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)

Difference between undeclared, undefined, and null

undeclared variables are variables that are created without the use of let, var, const. It is considered a global variable. undefined is encountered when a variable is declared but not assigned any value. null is an explicit value given to variables to signify that it does not have a value.

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.

What are stateful components?

If the behaviour of a component is dependent on the state of the component then it can be termed as stateful component. These stateful components are always class components and have a state that gets initialized in the constructor.

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.

What method does the unMounting phase contain?

It contains componentWillUnmount(), considered a cleanup method that is best used for invalidating timers, canceling network requests, or cleaning up any subscription

List some of the major advantages of React.

It increases the application's performance It can be conveniently used on the client as well as server side Because of JSX, code's readability increases React is easy to integrate with other frameworks like Meteor, Angular, etc Using React, writing UI test cases become extremely easy

What is a string literal?

It is a technique of formatting a string that use back ticks instead of single or double quotes. Variables can be referenced inside the string by using --> ${}

Advantages of "use strict"

Makes it impossible to accidentally create global variables. Makes assignments which would otherwise silently fail to throw an exception. Makes attempts to delete undeletable properties throw (where before the attempt would simply have no effect). Requires that function parameter names be unique. this is undefined in the global context. It catches some common coding bloopers, throwing exceptions. It disables features that are confusing or poorly thought out.

What's a typical use case for anonymous functions?

Preferably inside a callback and preferably if only used once.

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,

What is the purpose of cb 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.

constructor()

The first methods that is called in the mounting phase of the react lifecycle. It is the natural place to set up the initial state and other initial values

What is reconciliation?

When a component's props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one. When they are not equal, React will update the DOM. This process is called reconciliation.

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 is "use strict";? what are the advantages and disadvantages to using it?

'use strict' is a statement used to enable strict mode to entire scripts or individual functions. Strict mode is a way to opt into a restricted variant of JavaScript.

What is "key" prop and what is the benefit of using it in arrays of elements?

A key is a special string attribute you should include when creating arrays of elements. Key prop helps React identify which items have changed, are added, or are removed. Most often we use ID from our data as key:

Difference between: function Person(){}, var person = Person(), and var person = new Person()?

First option is just the syntax for creating a constructor. The capital P is a tip off. The second example is assigning the return value of Person() to person, however, constructors do not work in this way. The last example is the correct way to create an object/instance of a Person by using "new"

How to create components in React?

Function components and Class Components

Why is super(props) necessary in the constructor?

It allows component access to props coming. It isn't enough to just have it as an argument inside the constructor.

What are the features of React?

It uses the virtual DOM instead of the real DOM. It uses server-side rendering. It follows uni-directional data flow or data binding.

componentDidMount()

The componentDidMount() method is invoked immediately after the component is rendered. THis is where you run statements that require that the component is already placed in the DOM. Like fetching or adding event listeners.

When to use Pure Components?

Use Pure Components, in the case when the props and state changes are made to primitive type variable, state and props changes to reference variable may lead to incorrect results and inconsistent rendering

Have you ever used JavaScript templating? If so, what libraries have you used?

Yes, JSX. It most closes feels like JavaScript while also having a markup style syntax

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

What is the purpose of using super constructor with props argument?

A child class constructor cannot make use of this reference until super() method has been called. The same applies for ES6 sub-classes as well. The main reason of passing props parameter to super() call is to access this.props in your child constructors.

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,

Advantages of using Ajax

Better interactivity. New content from the server can be changed dynamically without the need to reload the entire page. Reduce connections to the server since scripts and stylesheets only have to be requested once. State can be maintained on a page. JavaScript variables and DOM state will persist because the main container page was not reloaded. Basically most of the advantages of an SPA.

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 are the three principles of redux?

Single source of truth. The global state of your application is stored in an object tree within a single store. State is read-only. The only way to change the state is to emit an action, an object describing what happened. Changes are made with pure functions.

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.

Features of React Pure Components

* Prevents re-rendering of Component if props or state is the same. * Takes care of "shouldComponentUpdate" implicitly *State and Props are Shallow Compared * Pure Components are more performant in certain cases

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. HOC can be used for many use cases: Code reuse, logic and bootstrap abstraction. Render hijacking. State abstraction and manipulation. Props manipulation.

What is a promise?

A promise is an object that may produce a single value sometime in the future: either a resolved value or a reason that it's not resolved (e.g., a network error occurred). A promise may be in one of 3 possible states: fulfilled, rejected, or pending. Promise users can attach callbacks to handle the fulfilled value or the reason for rejection.

Explain Ajax in as much detail as possible.

AJAX is short for Asynchronous Javascript + XML. The technique consists of making server requests for additional data without unloading the page, resulting in a better user experience. It allows the content on a web page to change dynamically without the need to reload the entire page. In practice, modern implementations commonly substitute use JSON instead of XML

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.

What's the difference between an attribute and property

Attributes are defined on the HTML markup === getAttribute is always the same despite changes on the DOM Property are defined on the DOM

What are the pros and cons of using Promises instead of callbacks?

Avoid callback hell which can be unreadable. Makes it easy to write sequential asynchronous code that is readable with .then(). Makes it easy to write parallel asynchronous code with Promise.all(). With promises, these scenarios which are present in callbacks-only coding, will not happen:Call the callback too earlyCall the callback too late (or never)Call the callback too few or too many timesFail to pass along any necessary environment/parametersSwallow any errors/exceptions that may happen

How to bind methods or event handlers in JSX callbacks?

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. 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. Arrow functions in callbacks: You can use arrow functions directly in the callbacks.

What is the difference between .call() and .apply()?

Both .call and .apply are used to invoke functions and the first parameter will be used as the value of this within the function. However, .call takes in comma-separated arguments as the next arguments while .apply takes in an array of arguments as the next argument. An easy way to remember this is C for call and comma-separated and A for apply and an array of arguments.

Why can't browsers read JSX?

Browsers can only read JavaScript objects but JSX in not a regular JavaScript object. Thus to enable a browser to read JSX, first, we need to transform JSX file into a JavaScript object using JSX transformers like Babel and then pass it to the browser.

What is children prop?

Children is a prop (this.props.children) that allow 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 a number of 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,

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 user, locale preference, UI theme need to be accessed in the application by many components.

Explain Hoisting in JavaScript?

Declaration of var variables are moved to the top when the code is executed. Functions declarations and their bodies are moved to the top. Hoisting is a term used to explain the behavior of variable declarations in your code. Variables declared or initialized with the var keyword will have their declaration "moved" up to the top of their module/function-level scope, which we refer to as hoisting. However, only the declaration is hoisted, the assignment (if there is one), will stay where it is. Note that the declaration is not actually moved - the JavaScript engine parses the declarations during compilation and becomes aware of declarations and their scopes. It is just easier to understand this behavior by visualizing the declarations as being hoisted to the top of their scope. Let's explain with a few examples.

Disadvantages of using Ajax

Dynamic webpages are harder to bookmark. Does not work if JavaScript has been disabled in the browser. Some webcrawlers do not execute JavaScript and would not see content that has been loaded by JavaScript. Webpages using Ajax to fetch data will likely have to combine the fetched remote data with client-side templates to update the DOM. For this to happen, JavaScript will have to be parsed and executed on the browser, and low-end mobile devices might struggle with this. Basically most of the disadvantages of an SPA.

What's the difference between feature detection, feature inference, and using the UA string Feature Detection

Feature detection involves working out whether a browser supports a certain block of code, and running different code depending on whether it does (or doesn't), so that the browser can always provide a working experience rather crashing/erroring in some browsers

Feature Inference

Feature inference checks for a feature just like feature detection, but uses another function because it assumes it will also exist. if (questionableObject.property){} in this case if questionableObject is undefined, this would crash

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.

Downsides of SPA

Heavier initial page load due to the loading of framework, app code, and assets required for multiple pages. There's an additional step to be done on your server which is to configure it to route all requests to a single entry point and allow client-side routing to take over from there. SPAs are reliant on JavaScript to render content, but not all search engines execute JavaScript during crawling, and they may see empty content on your page. This inadvertently hurts the Search Engine Optimization (SEO) of your app. However, most of the time, when you are building apps, SEO is not the most important factor, as not all the content needs to be indexable by search engines. To overcome this, you can either server-side render your app or use services such as Prerender to "render your javascript in a browser, save the static HTML, and return that to the crawlers".

Pure Functions should not introduce side effects.

If the application updates certain data that is observable outside the called function, it can be considered a side effect introduced by the function. Here are a few scenarios: Modifying any external variable or object property Logging data to the console Writing Data to a file Writing data to the network Triggering any external process Calling any other functions with side-effects Making Asynchronous Data Calls We need to avoid these side effects inside Pure Components.

What are stateless components?

If the behaviour is independent of its state then it can be a stateless component. You can use either a function or a class for creating stateless components. But unless you need to use a lifecycle hook in your components, you should go for function components. There are a lot of benefits if you decide to use function components here; they are easy to write, understand, and test, a little faster, and you can avoid the this keyword altogether.

Why should we not update the state directly?

Instead use setState() method. It schedules an update to a component's state object. When state changes, the component responds by re-rendering. This is considered mutating the state and it is not recommended because react compares the previous state with the current state. Mutated state will hold the same address in memory.

What are the major features of React?

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 are fragments?

It's common pattern in React which is used for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.

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

What is JSX?

JSX is a shorthand for JavaScript XML. This is a type of file used by React which utilizes the expressiveness of JavaScript along with HTML like template syntax. This makes the HTML file really easy to understand. This file makes applications robust and boosts its performance. Below is an example of JSX:

disadvantages of "use strict"

Many missing features that some developers might be used to. No more access to function.caller and function.arguments. Concatenation of scripts written in different strict modes might cause issues.

What is React?

React is a front-end JavaScript library developed by Facebook in 2011 It follows the component based approach which helps in building reusable UI components. It is used for developing complex and interactive web and mobile UI. Even though it was open-sourced only in 2015, it has one of the largest communities supporting it.

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 benefits of using pure functions

The Application calls for the same function multiple times with the same parameters — assume "add(10, 20)". After executing it multiple times, the Chrome V8 Engine tries to optimize the code further by storing the execution result of the following function call. On the next call to the same function, with the same parameter, instead of executing the function again, the cached result is returned. Hence enhancing the Application Performance.

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.

Benefits of single page app

The app feels more responsive and users do not see the flash between page navigations due to full-page refreshes. Fewer HTTP requests are made to the server, as the same assets do not have to be downloaded again for each page load. Clear separation of the concerns between the client and the server; you can easily build new clients for different platforms (e.g. mobile, chatbots, smart watches) without having to modify the server code. You can also modify the technology stack on the client and server independently, as long as the API contract is not broken.

What are Pure Components in React?

They are components that do not re-render when the value of state and props has been updated with the same values. If the value of the previous state or props and the new state or props is the same, the component is not re-rendered. Pure Components restricts the re-rendering ensuring the higher performance of the Component

UA String

This is a browser-reported string that allows the network protocol peers to identify the application type, operating system, software vendor or software version of the requesting software user agent. It can be accessed via navigator.userAgent. However, the string is tricky to parse and can be spoofed. For example, Chrome reports both as Chrome and Safari. So to detect Safari you have to check for the Safari string and the absence of the Chrome string. Avoid this method.

getDerivedStateFromProps()

This method is called right before rendering the elements in the DOM. This is the natural place to set the state object base on the initial props. Takes state as an argument and returns an object with changes to the state. Since this is a static variable, meaning that it belongs to the class, the keyword this is not allowed in the body of the method.

What is an SPA?

Web developers these days refer to the products they build as web apps, rather than websites. While there is no strict difference between the two terms, web apps tend to be highly interactive and dynamic, allowing the user to perform actions and receive a response to their action. Traditionally, the browser receives HTML from the server and renders it. When the user navigates to another URL, a full-page refresh is required and the server sends fresh new HTML to the new page. This is called server-side rendering. However, in modern SPAs, client-side rendering is used instead. The browser loads the initial page from the server, along with the scripts (frameworks, libraries, app code) and stylesheets required for the whole app. When the user navigates to other pages, a page refresh is not triggered. The URL of the page is updated via the HTML5 History API. New data required for the new page, usually in JSON format, is retrieved by the browser via AJAX requests to the server. The SPA then dynamically updates the page with the data via JavaScript, which it has already downloaded in the initial page load. This model is similar to how native mobile apps work.

Hw Virtual DOM works?

Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representation. 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.

How to create props proxy for HOC component?

You can add/edit props passed to the component using props proxy pattern like this:

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

What are the lifecycle methods of React?

getDerivedStateFromProps: Invoked right before calling render() and is invoked on every render. This exists for rare use cases where you need derived state. Worth reading if you need derived state. componentDidMount: Executed after first rendering and here 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 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. 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.


संबंधित स्टडी सेट्स

Constitutional Law Learning Questions Set 7

View Set

100 FACTS OF TEMPOROMANDIBULAR JOINT

View Set

Chapter 17 Monopolistic Competition

View Set

11.8.10 Remote Desktop & Assistance

View Set