React

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Why fragments are better than container divs?

- Fragments are a bit faster and use less memory by not creating an extra DOM node. This only has a real benefit on very large and deep trees. - Some CSS mechanisms like Flexbox and CSS Grid have a special parent-child relationships, and adding divs in the middle makes it hard to keep the desired layout. - The DOM Inspector is less cluttered.

What is the difference 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, 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.

What are the advantages of React?

- Increases the application's performance with Virtual DOM. - JSX makes code easy to read and write. - It renders both on client and server side (SSR). - Easy to integrate with frameworks (Angular, Backbone) since it is only a view library. - Easy to write unit and integration tests with tools such as Jest.

How events are different in React?

- React event handlers are named using camelCase, rather than lowercase. - With JSX you pass a function as the event handler, rather than a string.

What are the limitations of React?

- React is just a view library, not a full framework. - There is a learning curve for beginners who are new to web development. - Integrating React into a traditional MVC framework requires some additional configuration. - The code complexity increases with inline templating and JSX. - Too many smaller components leading to over engineering or boilerplate.

What are the lifecycle methods of React before 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.

What are the lifecycle methods of React after 16.3?

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

How to bind methods or event handlers in JSX callbacks?

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

How Virtual DOM works?

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 JSX?

A XML-like syntax extension to ECMAScript (the acronym stands for JavaScript XML).

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 synthetic events in React?

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 forward refs?

A feature that lets some components take a ref they receive, and pass it further down to a child.

What is children prop?

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.

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

What is Virtual DOM?

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.

What is state in React?

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. 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 is React?

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.

How do you render Array, Strings and Numbers in React 16 Version?

Arrays: Unlike older releases, you don't need to make sure render method return a single element in React16. You are able to return multiple sibling elements without a wrapping element by returning an array. Strings and Numbers: You can also return string and number type from the render method.

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.

Do Hooks replace render props and higher order components?

Both render props and higher-order components render only a single child but in most of the cases Hooks are a simpler way to serve this by reducing nesting in your tree.

What is the difference between Shadow DOM and Virtual DOM?

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 are controlled components?

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.

What are error boundaries in React v16

Error boundaries are components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. A class component becomes an error boundary if it defines a new lifecycle method called componentDidCatch(error, info) or static getDerivedStateFromError() :

What are Pure Components?

Exactly the same as React.Component except that it handles the shouldComponentUpdate() method for you. When props or state changes, PureComponent will do a shallow comparison on both props and state. Component on the other hand won't compare current props and state to next out of the box. Thus, the component will re-render by default whenever shouldComponentUpdate is called.

What is Flux?

Flux is an application design paradigm used as a replacement for the more traditional MVC pattern. It is not a framework or a library but a new kind of architecture that complements React and the concept of Unidirectional Data Flow. Facebook uses this pattern internally when working with React.

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.

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. React 16.8 Update: Hooks let you use state and other React features without writing classes.

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 will happen if you use props in initial state?

If the props on the component are changed without the component being refreshed, the new prop value will never be displayed because the constructor function will never update the current state of the component. The initialization of state from props only runs when the component is first created. Using props inside render method will update the value:

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.

Why should we not update the state directly?

If you try to update state directly then it won't re-render the component. Instead use setState() method. It schedules an update to a component's state object. When state changes, the component responds by re-rendering.

Is it possible to use async/await in plain React?

If you want to use async/await in React, you will need Babel and transform-async-to-generator plugin. React Native ships with Babel and a set of transforms.

What is the purpose of callback function as an argument of setState()?

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.

What is the recommended way for naming components?

It is recommended to name the component by reference instead of using displayName.

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. Let you group a list of children without adding extra nodes to the DOM.

What is the impact of indexes as keys?

Keys should be stable, predictable, and unique so that React can keep track of elements.

What are the different phases of component lifecycle?

Mounting: The component is ready to mount in the browser DOM. This phase covers initialization from constructor(), getDerivedStateFromProps(), render(), and componentDidMount() lifecycle methods. 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. Unmounting: In this last phase, the component is not needed and get 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 Render The component will render without any side-effects. This applies for Pure components and in this phase, React can pause, abort, or restart the render. 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(). Commit React works with the DOM and executes the final lifecycles respectively componentDidMount() for mounting, componentDidUpdate() for updating, and componentWillUnmount() for unmounting.

Do browsers understand JSX code?

No, browsers can't understand JSX code. You need a transpiler to convert your JSX to regular Javascript that browsers can understand. The most widely used transpiler right now is Babel.

What are the recommended ways for static type checking?

Normally we use PropTypes library (React.PropTypes moved to a prop-types package since React v15.5) for type checking in the React applications. For large code bases, it is recommended to use static type checkers such as Flow or TypeScript, that perform type checking at compile time and provide auto-completion features.

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

How do you access props in attribute quotes?

React (or JSX) doesn't support variable interpolation inside an attribute value. But you can put any JS expression inside curly braces as the entire attribute value.

Describe about data flow in react?

React implements one-way reactive data flow using props which reduce boilerplate and is easier to understand than traditional two-way data binding.

How error boundaries handled in React v15?

React v15 provided very basic support for error boundaries using unstable_handleError method. It has been renamed to componentDidCatch in React v16.

Why is a component constructor called only once?

React's reconciliation algorithm assumes that without any information to the contrary, if a custom component appears in the same place on subsequent renders, it's the same component as before, so reuses the previous instance rather than creating a new one.

What is strict mode in React?

React.StrictMode is a useful component for highlighting potential problems in an application. Just like <Fragment>, <StrictMode> does not render any extra DOM elements. It activates additional checks and warnings for its descendants. These checks apply for development mode only.

What are render props?

Render Props is a simple technique for sharing code between components using a prop whose value is a function. The below component uses render prop which returns a React element.

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

Special string attribute you should include when creating arrays of elements. Helps React identify which items have changed, are added, or are removed. 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.

Why you can't update props in React?

The React philosophy is that props should be immutable and top-down. This means that a parent can send any prop values to a child, but the child can't modify received props.

What is the recommended approach of removing an array element in react state?

The better approach is to use Array.prototype.filter() method.

How to write comments in React?

The comments in React/JSX are similar to JavaScript Multiline comments but are wrapped in curly braces.

How to listen to state changes?

The componentDidUpdate lifecycle method will be called when state changes. You can compare provided state and props values with current state and props to determine if something meaningful changed.

What is CRA and its benefits?

The create-react-app CLI tool allows you to quickly create & run React applications with no configuration step. Let's create Todo App using CRA: It includes everything we need to build a React app: - React, JSX, ES6, and Flow syntax support. - Language extras beyond ES6 like the object spread operator. - Autoprefixed CSS, so you don't need -webkit- or other prefixes. - A fast interactive unit test runner with built-in support for coverage reporting. - A live development server that warns about common mistakes. - A build script to bundle JS, CSS, and images for production, with hashes and sourcemaps.

How to use InnerHtml in React?

The dangerouslySetInnerHTML attribute is React's replacement for using innerHTML in the browser DOM. Just like innerHTML, it is risky to use this attribute considering cross-site scripting (XSS) attacks. You just need to pass a __html object as key and HTML text as value.

What is the lifecycle methods order in mounting?

The lifecycle methods are called in the following order when an instance of a component is being created and inserted into the DOM. - constructor() - static getDerivedStateFromProps() - render() - componentDidMount()

What are the exceptions on React component naming?

The lowercase tag names with a dot (property accessors) are still considered as valid component names.

What are uncontrolled components?

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.

Why we need to pass a function to setState()?

The reason behind for this is that setState() is an asynchronous operation. React batches state changes for performance reasons, so the state may not change immediately after setState() is called. That means you should not rely on the current state when calling setState() since you can't be sure what that state will be. The solution is to pass a function to setState(), with the previous state as an argument. By doing this you can avoid issues with the user getting the old state value on access due to the asynchronous nature of setState().

How to use styles in React?

The style attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM style JavaScript property, is more efficient, and prevents XSS security holes. Style keys are camelCased in order to be consistent with accessing the properties on DOM nodes in JavaScript (e.g. node.style.backgroundImage).

How do you memoize a component?

There are memoize libraries available which can be used on function components. For example moize library can memoize the component in another component. Update: Since React v16.6.0, we have a React.memo. It provides a higher order component which memoizes component unless the props change. To use it, simply wrap the component using React.memo before you use it.

What is the use of refs?

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.

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.

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.

How to apply validation on props in React?

When the application is running in development mode, React will automatically check all props that we set on components to make sure they have correct type. If the type is incorrect, React will generate warning messages in the console. It's disabled in production mode due to performance impact. The mandatory props are defined with isRequired. Examples: PropTypes.number, PropTypes.string, PropTypes.array, PropTypes.object, PropTypes.func, PropTypes.node, PropTypes.element, PropTypes.bool, PropTypes.symbol, PropTypes.any -> Note: In React v15.5 PropTypes were moved from React.PropTypes to prop-types library.

Why we need to be careful when spreading props on DOM elements??

When we spread props we run into the risk of adding unknown HTML attributes, which is a bad practice. Instead we can use prop destructuring with ...rest operator, so it will add only required props.

What will happen if you use setState in constructor?

When you use setState(), then apart from assigning to the object state React also re-renders the component and all its children. You would get error like this: Can only update a mounted or mounting component. So we need to use this.state to initialize variables inside constructor.

What is the difference between super() and super(props) in React using ES6 classes?

When you want to access this.props in constructor() then you should pass props to super() method.

Is it good to use setState() in componentWillMount() method?

Yes, it is safe to use setState() inside componentWillMount() method. But at the same it is recommended to avoid async initialization in componentWillMount() lifecycle method. componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state in this method will not trigger a re-render. Avoid introducing any side-effects or subscriptions in this method. We need to make sure async calls for component initialization happened in componentDidMount() instead of componentWillMount().

How you use decorators in React?

You can decorate your class components, which is the same as passing the component into a function. Decorators are flexible and readable way of modifying component functionality.

How to re-render the view when the browser is resized?

You can listen to the resize event in componentDidMount() and then update the dimensions (width and height). You should remove the listener in componentWillUnmount() method.

How to loop inside JSX?

You can simply use Array.prototype.map with ES6 arrow function syntax. This is because JSX tags are transpiled into function calls, and you can't use statements inside expressions. This may change thanks to do expressions which are stage 1 proposal.

How to make AJAX call and In which component lifecycle methods should I make an AJAX call?

You can use AJAX libraries such as Axios, jQuery AJAX, and the browser built-in fetch. You should fetch data in the componentDidMount() lifecycle method. This is so you can use setState() to update your component when the data is retrieved.

How to define constants in React?

You can use ES7 static field to define constant.

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, this is an equivalent to calling .bind. Apart from these two approaches, you can also pass arguments to a function which is defined as arrow function

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

How to combine multiple inline style objects?

You can use spread operator in regular React

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, instead, pass the function itself without parenthesis

How to update a component every second?

You need to use setInterval() to trigger the change, but you also need to clear the timer when the component unmounts to prevent errors and memory leaks.

How to import and export components using react and ES6?

You should use default for exporting the components.

How to conditionally apply class attributes?

You shouldn't use curly braces inside quotes because it is going to be evaluated as a string. Instead you need to move curly braces outside (don't forget to include spaces between class names)

Why React uses className over class 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.


Set pelajaran terkait

AHIMA data quality characteristics

View Set

Present tense of -er and -ir verbs

View Set

2017 National Electrical Code Article 200 Use and Identification of Grounded Conductors.

View Set

*Chapter 6 Personal Finance Consumer Credit

View Set

Chapter 7: Inventory and Cost of Goods Sold

View Set

Maco/Micro Economics Chapter 1-4

View Set