React Flashcards

1
Q

JSX

Nested JSX elements

A

In order for the code to compile, a JSX expression must have exactly one outermost element. In the below block of code the <a> tag is the outermost element.</a>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

JSX

JSX Syntax and JavaScript

A

JSX is a syntax extension of JavaScript. It’s used to create DOM elements which are then rendered in the React DOM.

A JavaScript file containing JSX will have to be compiled before it reaches a web browser. The code block shows some example JavaScript code that will need to be compiled.

import React from 'react';
import ReactDOM from 'react-dom';
 
ReactDOM.render(<h1>Render me!</h1>, document.getElementById('app'));
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

JSX

Multiline JSX Expression

A

A JSX expression that spans multiple lines must be wrapped in parentheses: ( and ). In the example code, we see the opening parentheses on the same line as the constant declaration, before the JSX expression begins. We see the closing parentheses on the line following the end of the JSX expression.

const myList = (
  <ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
  </ul>
);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

JSX

JSX syntax and HTML

A

In the block of code we see the similarities between JSX syntax and HTML: they both use the angle bracket opening and closing tags (<h1> and </h1>).

When used in a React component, JSX will be rendered as HTML in the browser.

const title = <h1>Welcome all!</h1>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

JSX

JSX attributes

A

The syntax of JSX attributes closely resembles that of HTML attributes. In the block of code, inside of the opening tag of the <h1> JSX element, we see an id attribute with the value “example”.

const example = <h1 id="example">JSX Attributes</h1>;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

JSX

ReactDOM JavaScript library

A

The JavaScript library react-dom, sometimes called ReactDOM, renders JSX elements to the DOM by taking a JSX expression, creating a corresponding tree of DOM nodes, and adding that tree to the DOM.

The code example begins with ReactDOM.render(). The first argument is the JSX expression to be compiled and rendered and the second argument is the HTML element we want to append it to.

ReactDOM.render(
  <h1>This is an example.</h1>, 
  document.getElementById('app')
);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

JSX

Embedding JavaScript in JSX

A

JavaScript expressions may be embedded within JSX expressions. The embedded JavaScript expression must be wrapped in curly braces.

In the provided example, we are embedding the JavaScript expression 10 * 10 within the <h1> tag. When this JSX expression is rendered to the DOM, the embedded JavaScript expression is evaluated and rendered as 100 as the content of the <h1> tag.

let expr = <h1>{10 * 10}</h1>;
// above will be rendered as <h1>100</h1>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

JSX

The Virtual Dom

A

React uses Virtual DOM, which can be thought of as a blueprint of the DOM. When any changes are made to React elements, the Virtual DOM is updated. The Virtual DOM finds the differences between it and the DOM and re-renders only the elements in the DOM that changed. This makes the Virtual DOM faster and more efficient than updating the entire DOM.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

JSX

JSX className

A

In JSX, you can’t use the word class! You have to use className instead. This is because JSX gets translated into JavaScript, and class is a reserved word in JavaScript.

When JSX is rendered, JSX className attributes are automatically rendered as class attributes.

// When rendered, this JSX expression...
const heading = <h1 className="large-heading">Codecademy</h1>;

// ...will be rendered as this HTML
<h1 class="large-heading">Codecademy</h1>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

JSX

JSX and conditional

A

In JSX, && is commonly used to render an element based on a boolean condition. && works best in conditionals that will sometimes do an action, but other times do nothing at all.

If the expression on the left of the && evaluates as true, then the JSX on the right of the && will be rendered. If the first expression is false, however, then the JSX to the right of the && will be ignored and not rendered.

// All of the list items will display if
// baby is false and age is above 25
const tasty = (
  <ul>
    <li>Applesauce</li>
    { !baby && <li>Pizza</li> }
    { age > 15 && <li>Brussels Sprouts</li> }
    { age > 20 && <li>Oysters</li> }
    { age > 25 && <li>Grappa</li> }
  </ul>
);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

JSX

JSX conditionals

A

JSX does not support if/else syntax in embedded JavaScript. There are three ways to express conditionals for use with JSX elements:

a ternary within curly braces in JSX
an if statement outside a JSX element, or
the && operator.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

JSX

Embedding JavaScript code in JSX

A

Any text between JSX tags will be read as text content, not as JavaScript. In order for the text to be read as JavaScript, the code must be embedded between curly braces { }.

<p>{ Math.random() }</p>

// Above JSX will be rendered something like this: 
<p>0.88</p>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

JSX

JSX element event listeners

A

In JSX, event listeners are specified as attributes on elements. An event listener attribute’s name should be written in camelCase, such as onClick for an onclick event, and onMouseOver for an onmouseover event.

An event listener attribute’s value should be a function. Event listener functions can be declared inline or as variables and they can optionally take one argument representing the event.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

JSX

Setting JSX attribute values with embedded JavaScript

A

When writing JSX, it’s common to set attributes using embedded JavaScript variables.

const introClass = "introduction";
const introParagraph = <p className={introClass}>Hello world</p>;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

JSX

JSX .map() method

A

The array method map() comes up often in React. It’s good to get in the habit of using it alongside JSX.

If you want to create a list of JSX elements from a given array, then map() over each element in the array, returning a list item for each one.

const strings = ['Home', 'Shop', 'About Me'];

const listItems = strings.map(string => <li>{string}</li>);

<ul>{listItems}</ul>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

JSX

JSX empty elements syntax

A

In JSX, empty elements must explicitly be closed using a closing slash at the end of their tag: <tagName></tagName>.

A couple examples of empty element tags that must explicitly be closed include <br></br> and <img></img>.

<br />
<img src="example_url" />
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

JSX

React.createElement() Creates Virtual DOM Elements

A

The React.createElement() function is used by React to actually create virtual DOM elements from JSX. When the JSX is compiled, it is replaced by calls to React.createElement().

You usually won’t write this function yourself, but it’s useful to know about.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

JSX

JSX key attribute

A

In JSX elements in a list, the key attribute is used to uniquely identify individual elements. It is declared like any other attribute.

Keys can help performance because they allow React to keep track of whether individual list items should be rendered, or if the order of individual items is important.

<ul>
  <li key="key1">One</li>
  <li key="key2">Two</li>
  <li key="key3">Three</li>
  <li key="key4">Four</li>
</ul>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

React Components

render() Method

A

React class components must have a render() method. This method should return some React elements created with JSX.

React class components need to inherit from the React.Component base class and have a render() method. Other than that, they follow regular JavaScript class syntax.

This example shows a simple React class component.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

React Components

Importing React and React Components

A

In order to use React, we must first import the React library. When we import the library, it creates an object that contains properties needed to make React work, including JSX and creating custom components.

A React component is a reusable piece of code used to define the appearance, behavior, and state of a portion of a web app’s interface. Components are defined as functions or as classes. Using the component as a factory, an infinite number of component instances can be created.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

React Components

JSX Capitalization

A

React requires that the first letter of components be capitalized. JSX will use this capitalization to tell the difference between an HTML tag and a component instance. If the first letter of a name is capitalized, then JSX knows it’s a component instance; if not, then it’s an HTML element.

// This is considered a component by React.
<ThisComponent />
  
// This is considered a JSX HTML tag. 
<div>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

React Components

ReactDOM.render()

A

ReactDOM.render()‘s first argument is a component instance. It will render that component instance.

In this example, we will render an instance of MyComponent.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

React Components

Multi-line JSX Expressions

A

Parentheses are used when writing a multi-line JSX expression. In the example, we see that the component’s render() method is split over multiple lines. Therefore it is wrapped in parentheses.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

React Components

Code in render()

A

A React component can contain JavaScript before any JSX is returned. The JavaScript before the return statement informs any logic necessary to render the component.

In the example code, we see JavaScript prior to the return statement which rounds the value to an integer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

React Components

Object Properties As Attribute Values

A

In React, JSX attribute values can be set through data stored in regular JavaScript objects. We see this in the example block of code.

In our code example we first see our JavaScript object seaAnemones and the values stored with this image. We then see how these stored values are used to set the <img></img> attributes in our JSX expression for the SeaAnemones component.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Components Interacting

Returning HTML Elements and Components

A

A class component’s render() method can return any JSX, including a mix of HTML elements and custom React components.

In the example, we return a <Logo></Logo> component and a “vanilla” HTML title.

This assumes that <Logo></Logo> is defined elsewhere.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Components Interacting

React Component File Organization

A

It is common to keep each React component in its own file, export it, and import it wherever else it is needed. This file organization helps make components reusable. You don’t need to do this, but it’s a useful convention.

In the example, we might have two files: App.js, which is the top-level component for our app, and Clock.js, a sub-component.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Components Interacting

this.props

A

React class components can access their props with the this.props object.

In the example code below, we see the <Hello> component being rendered with a firstName prop. It is accessed in the component’s render() method with this.props.firstName.</Hello>

This should render the text “Hi there, Kim!”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Components Interacting

defaultProps

A

A React component’s defaultProps object contains default values to be used in case props are not passed. If a prop is not passed to a component, then it will be replaced with the value in the defaultProps object.

In the example code, defaultProps is set so that profiles have a fallback profile picture if none is set. The <MyFriends> component should render two profiles: one with a set profile picture and one with the fallback profile picture.</MyFriends>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

Lifecycle Methods

Component Mount

A

A React component mounts when it renders to the DOM for the first time. If it’s already mounted, a component can be rendered again if it needs to change its appearance or content.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Lifecycle Methods

Unmounting Lifecycle Method

A

React supports one unmounting lifecycle method, componentWillUnmount, which will be called right before a component is removed from the DOM.

componentWillUnmount() is used to do any necessary cleanup (canceling any timers or intervals, for example) before the component disappears.

Note that the this.setState() method should not be called inside componentWillUnmount() because the component will not be re-rendered.

 componentWillUnmount(prevProps, prevState) {
    clearInterval(this.interval);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Lifecycle Methods

Component Mounting Phase

A

A component “mounts” when it renders for the first time. When a component mounts, it automatically calls these three methods, in the order of:

  1. constructor()
  2. render()
  3. componentDidUpdate()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

Lifecycle Methods

Lifecycle Phases

A

There are three categories of lifecycle methods: mounting, updating, and unmounting.

A component “mounts” when it renders for the first time. This is when mounting lifecycle methods get called.

The first time that a component instance renders, it does not update. Starting with the second render, a component updates every time that it renders.

A component’s unmounting period occurs when the component is removed from the DOM. This could happen if the DOM is rerendered without the component, or if the user navigates to a different website or closes their web browser.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

Lifecycle Methods

Mounting Lifecycle Methods

A

React supports three mounting lifecycle methods for component classes: componentWillMount(), render(), and componentDidMount(). componentWillMount() will be called first followed by the render() method and finally the componentDidMount() method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Lifecycle Methods

Updating Lifecycle Method

A

When a component updates, shouldComponentUpdate() gets called after componentWillReceiveProps(), but still before the rendering begins. It automatically receives two arguments: nextProps and nextState.

shouldComponentUpdate() should return either true or false. The best way to use this method is to have it return false only under certain conditions. If those conditions are met, then your component will not update.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Hooks

Function Components

A

In React, you can use a function as a component instead of a class. Function components receive props as a parameter.

In the example code, we show two equivalent components: one as a class and one as a function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

Hooks

Why Hooks?

A

Hooks are functions that let us “hook into” state and lifecycle functionality in function components.

Hooks allow us to:

  • reuse stateful logic between components
  • simplify and organize our code to separate concerns, rather allowing unrelated data to get tangled up together
  • avoid confusion around the behavior of the this keyword
  • avoid class constructors, binding methods, and related advanced JavaScript techniques
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

Hooks

Rules for Using Hooks

A

There are two main rules to keep in mind when using Hooks:

Only call Hooks from React function components.
Only call Hooks at the top level, to be sure that Hooks are called in the same order each time a component renders.
Common mistakes to avoid are calling Hooks inside of loops, conditions, or nested functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

Hooks

The State Hook

A

The useState() Hook lets you add React state to function components. It should be called at the top level of a React function definition to manage its state.

initialState is an optional value that can be used to set the value of currentState for the first render. The stateSetter function is used to update the value of currentState and rerender our component with the next state value.

const [currentState, stateSetter] = useState(initialState);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

Hooks

State Setter Callback Function

A

When the previous state value is used to calculate the next state value, pass a function to the state setter. This function accepts the previous value as an argument and returns an updated value.

If the previous state is not used to compute the next state, just pass the next state value as the argument for the state setter.

41
Q

Hooks

Multiple State Hooks

A

useState() may be called more than once in a component. This gives us the freedom to separate concerns, simplify our state setter logic, and organize our code in whatever way makes the most sense to us!

42
Q

Hooks

Side Effects

A

The primary purpose of a React component is to return some JSX to be rendered. Often, it is helpful for a component to execute some code that performs side effects in addition to rendering JSX.

In class components, side effects are managed with lifecycle methods. In function components, we manage side effects with the Effect Hook. Some common side effects include: fetching data from a server, subscribing to a data stream, logging values to the console, interval timers, and directly interacting with the DOM.

43
Q

Hooks

The Effect Hook

A

After importing useEffect() from the ‘react’ library, we call this Hook at the top level of a React function definition to perform a side effect. The callback function that we pass as the first argument of useEffect() is where we write whatever JavaScript code that we’d like React to call after each render.

44
Q

Hooks

Effect Cleanup Functions

A

The cleanup function is optionally returned by the first argument of the Effect Hook.

If the effect does anything that needs to be cleaned up to prevent memory leaks, then the effect returns a cleanup function. The Effect Hook will call this cleanup function before calling the effect again as well as when the component is being unmounted from the DOM.

45
Q

Hooks

Multiple Effect Hooks

A

useEffect() may be called more than once in a component. This gives us the freedom to individually configure our dependency arrays, separate concerns, and organize our code in whatever way makes the most sense to us!

46
Q

Hooks

Effect Dependency Array

A

The dependency array is used to tell the useEffect() method when to call our effect.

By default, with no dependency array provided, our effect is called after every render. An empty dependency array signals that our effect never needs to be re-run. A non-empty dependency array signals to the Effect Hook that it only needs to call our effect again when the value of one of the listed dependencies has changed.

47
Q

Stateless Components From Stateful Components

Stateful and Stateless Components

A

In React, a stateful component is a component that holds some state. Stateless components, by contrast, have no state. Note that both types of components can use props.

In the example, there are two React components. The Store component is stateful and the Week component is stateless.

48
Q

Stateless Components From Stateful Components

React Programming Pattern

A

One of the most common programming patterns in React is to use stateful parent components to maintain their own state and pass it down to one or more stateless child components as props. The example code shows a basic example.

49
Q

Stateless Components From Stateful Components

Changing Props and State

A

In React, a component should never change its own props directly. A parent component should change them.

State, on the other hand, is the opposite of props: a component keeps track of its own state and can change it at any time.

The example code shows a component that accepts a prop, subtitle, which never changes. It also has a state object which does change.

50
Q

Stateless Components From Stateful Components

Passing State Change Functions as Props

A

If a React parent component defines a function that changes its state, that function can be passed to a child component and called within the component to updating the parent component’s state.

In this example, because this.setState() causes the Name component to re-render, any change to the <input></input> will update the Name component’s state, causing a new render and displaying the new state value to the <p> tag content.

51
Q

Stateless Components From Stateful Components

Event Handlers and State in React

A

Event handler functions in React are often used to update state. These handler functions often receive an event as an argument, which is used to update state values correctly.

In the example code, we use event.target.value to get the input’s value.

52
Q

Stateless Components From Stateful Components

Using Stateless Updaters and Presenters

A

A common React programming pattern is to use a parent stateful component to manage state and define state-updating methods. Then, it will render stateless child components.

One or more of those child components will be responsible for updating the parent state (via methods passed as props). One or more of those child components will be responsible for displaying that state.

In the example code, StatefulParent renders <InputComponent> to change its state and uses <DisplayComponent> to display it.</DisplayComponent></InputComponent>

53
Q

Additional React Basics

React CSS Styles

A

React supports inline CSS styles for elements. Styles are supplied as a style prop with a JavaScript object.

54
Q

Additional React Basics

Style Names And Values

A

In React, style names are written in “camelCase”, unlike in CSS where they are hyphenated. In most cases, style values are written as strings. When entering numeric values, you don’t have to enter px because React automatically interprets them as pixel values.

55
Q

Additional React Basics

Presentational and Container Components

A

A common programming pattern in React is to have presentational and container components. Container components contain business logic (methods) and handle state. Presentational components render that behavior and state to the user.

In the example code, CounterContainer is a container component and Counter is a presentational component.

56
Q

Additional React Basics

Static Property

A

In React, prop types are set as a static property (.propTypes) on a component class or a function component. .propTypes is an object with property names matching the expected props and values matching the expected value of that prop type. The code snippet above demonstrates how .propTypes can be applied.

57
Q

Additional React Basics

.isRequired

A

To indicate that a prop is required by the component, the property .isRequired can be chained to prop types. Doing this will display a warning in the console if the prop is not passed. The code snippet above demonstrates the use of .isRequired.

MyComponent.propTypes = {
  year: PropTypes.number.isRequired
};
58
Q

Additional React Basics

Type Checking

A

In React, the .propTypes property can be used to perform type-checking on props. This gives developers the ability to set rules on what data/variable type each component prop should be and to display warnings when a component receives invalid type props.

In order to use .propTypes, you’ll first need to import the prop-types library.

import PropTypes from 'prop-types';
59
Q

Additional React Basics

Controlled vs. Uncontrolled Form Fields

A

In React, form fields are considered either uncontrolled, meaning they maintain their own state, or controlled, meaning that some parent maintains their state and passes it to them to display. Usually, the form fields will be controlled.

The example code shows an uncontrolled and controlled input.

60
Q

Additional React Basics

Controlled Components

A

A controlled form element in React is built with a change handler function and a value attribute.

61
Q

Learn Advanced React

React Development Tools

A

React Dev Tools
React Developer Tools is a browser extension that helps debug React Apps by allowing developers to view components and view/edit component properties and state.

Components and Profiler
React Dev Tools creates two new tabs in Chrome Dev Tools: Components, and Profiler.

Components tab
The Components tab from React Dev Tools gives developers the ability to update a React components state and props.

Debugger
With the debugger attached and running, developers can inspect state, as well as keep track of function calls with the call stack.

62
Q

Advanced React: Custom Hooks

The Effect Hook

A

After importing useEffect() from the ‘react’ library, we call this Hook at the top level of a React function definition to perform a side effect. The callback function that we pass as the first argument of useEffect() is where we write whatever JavaScript code that we’d like React to call after each render.

63
Q

Advanced React: Custom Hooks

Rules for Using Hooks

A

There are two main rules to keep in mind when using Hooks:

Only call Hooks from React function components.
Only call Hooks at the top level, to be sure that Hooks are called in the same order each time a component renders.
Common mistakes to avoid are calling Hooks inside of loops, conditions, or nested functions.

64
Q

Advanced React: Custom Hooks

Effect hooks

A

Effect hooks are useful for performing “side effects” after render such as fetching data and reacting to state changes.

65
Q

Advanced React: Custom Hooks

Effect Dependency Array

A

The dependency array is used to tell the useEffect() method when to call our effect.

By default, with no dependency array provided, our effect is called after every render. An empty dependency array signals that our effect never needs to be re-run. A non-empty dependency array signals to the Effect Hook that it only needs to call our effect again when the value of one of the listed dependencies has changed.

66
Q

Advanced React: Custom Hooks

Custom Hooks

A

Custom Hooks are JavaScript functions that make use of other hooks, follow the rules of hooks, and whose names begin with use. Custom hooks are simply a convention and the programmer can decide what they do and what they return.

The provided example is from the Playing Hooky project. This custom hook changes the page’s appearance to “dark” or “light” mode while providing the current theme value for use elsewhere in the application.

67
Q

Advanced React: Custom Hooks

Use of Custom Hooks

A

Custom hooks have many benefits. They:

  • Allow code to be abstracted
  • Hide complex logic
  • Allow stateful logic to be reused between multiple components
68
Q

Advanced React: Context

Context Providers

A

React Context objects include a .Provider property that is a React component. It takes in a value prop to be made available to all its descendent components.

69
Q

Advanced React: Context

Context

A

Context is a feature of React that allows us to create a piece of state that any component within an area of your application can subscribe to.

70
Q

Advanced React: Context

Using Context Values

A

Descendents of a Context Provider may subscribe to the Provider’s data by passing the Context object to React’s useContext() hook.

71
Q

Advanced React: Context

Creating Contexts

A

The React.createContext() function creates and returns a React Context object.

72
Q

Advanced React: Context

Dynamic Context Values

A

A Context’s .Provider component may provide both a state value and its updater function via the value prop.

73
Q

Advanced React: Context

Context Wrappers

A

Some React applications use a dedicated “wrapper” component around a Context Provider to set up state for the Context. Doing so can help standardize setting up state for each usage of the Provider.

74
Q

Advanced React: Context

Multiple Providers

A

A .Provider component can be used in multiple places in your application to provide different values for that sub tree.

75
Q

Advanced React: Context

Prop Drilling

A

Prop drilling is the term for when a piece of data is passed as a prop through a large number of components in a React application.

76
Q

Advanced React: Context

Downsides of Prop Drilling

A

Downsides of prop drilling include components being harder to understand and excess rerenders of components that pass props without using them.

77
Q

Advanced React: Error Boundaries

What Is an Error Boundary?

A

Error boundaries are React components that wrap sections of a React application, catching runtime errors anywhere in their child component tree. They have three primary features:

  • Displaying a backup user-interface (a “fallback UI”)
  • Logging errors
  • Allowing the broken component to recover
78
Q

Advanced React: Error Boundaries

When to Use Error Boundaries?

A

Error boundaries should be used as close as possible to the parts of your application that can crash your application due to runtime errors.

Common places to use error boundaries are around new features that have not been thoroughly tested.

79
Q

Advanced React: Error Boundaries

How Do Error Boundaries Render a Fallback UI?

A

The static getDerivedStateFromError() lifecycle method is used to update the error boundary’s error state and trigger a fallback UI to be rendered.

This lifecycle method is invoked after an error has been thrown by a descendant component, receiving the error that was thrown as an argument. It should then return the error boundary’s next this.state value which may be used to determine what to render: a provided fallback UI or the default wrapped component tree.

80
Q

Advanced React: Error Boundaries

Why Are Error Boundaries Class Components?

A

React components become error boundaries once they implement one (or both) of the lifecycle methods static getDerivedStateFromError() and/or componentDidCatch(). In order to use these lifecycle methods, the error boundary must be a class component.

81
Q

Advanced React: Error Boundaries

How Does the <ErrorBoundary> Component From react-error-boundary Log Errors?

A

The ErrorBoundary component from react-error-boundary accepts an onError prop whose value should be a callback function that will be called when an error is caught.

This function receives two parameters:

  1. error — the error that was thrown with a .message property
  2. errorInfo — an object with a .componentStack property containing the stack of rendered components that led to the error
82
Q

Advanced React: Error Boundaries

What Is the react-error-boundary Package?

A

The react-error-boundary package exports an ErrorBoundary component. Among other things, it can be wrapped around a component tree to render a fallback UI and log errors in the event that a runtime error occurs.

83
Q

Advanced React: Error Boundaries

How Does the <ErrorBoundary> Component from react-error-boundary Render a Fallback?

A

The ErrorBoundary component from react-error-boundary accepts a FallbackComponent prop whose value should be a React component to render as a fallback UI when an error occurs.

The component passed as the FallbackComponentwill receive two props:

  1. error — the error that was thrown with a .message property
  2. resetErrorBoundary — a callback function to reset the error boundary
83
Q

Advanced React: Error Boundaries

How Does the <ErrorBoundary> Component from react-error-boundary Render a Fallback?

A

The ErrorBoundary component from react-error-boundary accepts a FallbackComponent prop whose value should be a React component to render as a fallback UI when an error occurs.

The component passed as the FallbackComponentwill receive two props:

  1. error — the error that was thrown with a .message property
  2. resetErrorBoundary — a callback function to reset the error boundary
84
Q

Advanced React: Error Boundaries

Should I Create My Own <ErrorBoundary> or Use an Existing One?

A

Typically, error boundaries are created once and used multiple times throughout the application. It’s common to use third-party error boundary implementations such as the react-error-boundary component.

85
Q

How Do Error Boundaries Log Errors?

How Do Error Boundaries Log Errors?

A

The componentDidCatch() lifecycle method used for error logging. It is called by React after an error has been thrown by one of its descendants. It receives an error object representing the thrown error. It also receives an errorInfo object with a .componentStack property containing the stack of rendered components that led to the error.

86
Q

Advanced React: Optimization

The React Profiler

A

The React profiler browser extension allows developers to record a session while using a React app in development mode. Once recorded, the profiler displays a flame graph, alongside other information on how React rendered each component.

87
Q

Advanced React: Optimization

The React profiler flame graph

A

A flame graph in the React profiler displays all components that were rendered during a session. Components that took longer to render are displayed in yellow, while ones that took less time to render are displayed in blue.

88
Q

Advanced React: Optimization

Memoization

A

Memoization prevents rerunning expensive operations by returning a cached result when given the same inputs as a past operation.

89
Q

Advanced React: Optimization

Memoizing values

A

React provides the useMemo() hook to memoize values. It takes two arguments, a function that returns a value, and a list of dependencies. Given the same list of dependencies, useMemo() will return a memoized value.

90
Q

Advanced React: Optimization

Higher order components

A

A higher order component is a component that takes in a component, adds functionality, then returns a new component with extra functionality.

91
Q

Advanced React: Optimization

Memoizing React components

A

React.memo() memoizes a React component. It takes a React component as an argument, then when given the same props, it will prevent React from re-rendering the provided component even when its parent re-renders.

92
Q

Advanced React: Optimization

Memoizing functions

A

React provides the useCallback() hook to memoize functions. It takes two arguments, a function, and a list of dependencies. Given the same list of dependencies, useCallback() will return a memoized function.

93
Q

Advanced React: Optimization

Code splitting

A

Code splitting is the act of separating code from the main JavaScript bundle in a React app to allow the main bundle to be smaller which usually reduces download, parsing, and execution time.

94
Q

Advanced React: Optimization

Chunks

A

When a library or a component is split out from the main JavaScript bundle.js file, it is called a chunk.

95
Q

Advanced React: Optimization

Code splitting a module

A

The import() function imports a module while instructing the bundler to create a separate chunk for the imported module. import() takes one argument, which is the path of a module. import() returns a JavaScript Promise.

96
Q

Advanced React: Optimization

Code splitting a component

A

The React.lazy() function imports a React component while instructing the bundler to create a separate chunk for the imported component. React.lazy() takes one argument, a function that returns an import(), which takes a path to a React component as its argument.

97
Q

Advanced React: Optimization

Suspense

A

The <Suspense> React component wraps components imported with React.lazy(). <Suspense> instructs React to load the rest of the React app and to display a loading state while the React component is downloaded and rendered. <Suspense> takes one prop named fallback, which is a React component shown while its lazily loaded children are unavailable.</Suspense></Suspense></Suspense>