React Tutorial Flashcards

1
Q

What is React?

A

Short definition
React is a JavaScript library for building User Interfaces.

Longer definition
React is a JavaScript library that is only responsible for the view layer of your application.
This means it is only responsible for rendering your User Interface (such as the text, text boxes, buttons, etc.) as well as updating the UI whenever it changes.

For example, say you’re building an e-commerce website and would like to maintain the number of items in the shopping bag as the user adds and removes items. React makes it easier for you to specify that you’d like to show the number of items in the shopping bag: {items.length}.
React will display that (the number of items in the shopping bag) and update it whenever it changes.

It also allows you to reuse this logic in another part of your UI. Say, for example, on the payment page; you can reuse the same logic without having to re-write it.

When learning React (or any other frontend library), it would seem overcomplicated or over-engineered. It is normal to feel that way because the benefit of these libraries is primarily visible when you build medium-sized or large web applications with several team members. So keep that in mind when learning and remember that the goal is to write maintainable and efficient code.

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

What’s the difference between a framework and a library? Which is React?

A

The difference between a library and a framework is that a library only helps you in one aspect. In contrast, a framework helps you in many aspects. Let’s take an example:

  • React is a library because it only takes care of your UI.
  • Angular, on the other hand, is a framework because it handles much more than the UI (It handles Dependency Injection, CSS encapsulation, etc.)

React itself is not a UI Library as in it does not give you beautifully designed buttons or cards.
It helps you manage complicated UI but does not come with a design system.
It will be up to you to choose a design library or use CSS to make it look nice and user-friendly.

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

Why must we import React?

A

Because React is not part of the browser. Every JavaScript file is a standalone module, meaning variables, functions, and imports in one file/module do not affect other files/modules.

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

What’s the difference between a method and a property?

A

A method is a function you need to call with parentheses, whereas a property is a value often pre-calculated.

Eg: React version property
console.log(React.version); //”18.1.0”

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

What’s the cost of importing React?

A

The cost of importing React is approximately 6KB.

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

Why do we use className and not class when changing an element’s class in React?

A

Because the keyword class in JavaScript is reserved and is used for creating a JavaScript class that can be called with new (not a CSS class).

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

What’s the difference between document.createElement and React.createElement?

A

document.createElement returns a DOM element (for example a div or an h1). Whereas React.createElement returns an object that represents the DOM element.
The object looks something like this:

const element = React.createElement(“h1”);
//returns an object similar to this one:
{
type: ‘h1’,
props: {}
}

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

Why does React.createElement return an object rather than the DOM element itself?

A

Because React operates a Virtual DOM. A virtual DOM is when a representation of the UI is kept in memory and synced with the DOM. So React.createElement returns an object rather than a DOM element because this allows React to perform performance optimizations (such as the Virtual DOM).

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

What is a React Element?

A

In React, an Element is the smallest building block.

It represents what the smallest piece of your User Interface will look like. In its simplest example, that could be a paragraph with the text Welcome inside of it (<p>Welcome</p>).

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

What are the three parameters in React.createElement?

A

React.createElement(type, options, children)

Eg: React.createElement(‘h1’, {className: ‘hero-title’}, ‘Welcome to our supermarket’)

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

What is the ReactDOM?

A

ReactDOM is the glue between React and the DOM.
React creates a virtual representation of your User Interface (in what we call a Virtual DOM). Then ReactDOM is the library that efficiently updates the DOM based on that Virtual DOM.

The Virtual DOM exists to figure out which parts of the UI need to be updated and then batch these changes together. ReactDOM receives those instructions from React and then efficiently updates the DOM.

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

Why is it a separate library?

A

A few years ago, React, and ReactDOM were part of the same library called React.
However, they got split into two separate libraries: React and ReactDOM, to allow for the launch of React Native.

React Native is the glue between React and native apps. React Native is outside the scope of this course but as you can see, React is the library that lets you write reusable UI and then:

ReactDOM makes this UI visible in the browser.
React Native makes this UI visible in a native app.
It’s important to remember that the React library has nothing to do with a web browser:

ReactDOM binds the idea of React to a web browser (example: Firefox, Chrome, Safari, Edge, etc.).
Whereas React Native binds the idea of React to a native app (example: native android, native iOS).

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

What is Reconciliation?

A

React is creating the virtual representation of your UI in the memory, and then ReactDOM receives that and syncs your UI (and the changes to it) to the DOM. This process is called reconciliation.

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

How do you install React and ReactDOM?

A

npm install react react-dom

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

How much does ReactDOM weigh?

A

130kb

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

We use ReactDOM to render (visualize) our React Elements (UI) on the page.
To do that, you have to tell ReactDOM where to render these elements.
What do we call that element?

A

We call that element the root.
This is a <div> element with an id of root or app-root or react-root or whatever name you prefer.
Let’s go with root for this example:

<div></div>

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

How can we render our React Element?

A

import {createRoot} from “react-dom/client”;

const root = document.querySelector(“#root”);
createRoot(root).render(React.createElement(“p”, {className: ‘title’}, “Hello World”));

Let’s break the code down:

  1. We start by getting a reference to the root element from the page (using querySelector or getElementById).
  2. We create the root of the React app using createRoot(root).
  3. On the result of createRoot(root), we call .render() and pass to it our React element.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Why do we use JSX?

A

When working with React, you will need to use React.createElement to represent your UI. However, as you may have seen, the syntax is long. It will become even longer and more tedious when you start having more complicated UI.

React uses a special syntax called JSX to solve that issue.
This JSX syntax may look similar to HTML, but it is NOT HTML.

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

What does the following get translated to?

import React from “react”;

const title = <h1>Hello World</h1>

A

import React from “react”;

const title = React.createElement(“h1”, {}, “Hello World”);

Always remember that the JSX that you write is being converted to React.createElement.
So, JSX is created to make it easier for you to describe your UI.

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

Is JSX part of the browser?

A

No, your browser cannot understand JSX because it’s a syntax created by React.
You will need a tool (such as babel) to convert your JSX code to normal JavaScript (which will contain the React.createElement calls).

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

Since you can essentially think of a JSX element as if it were an object, what can you do with it?

A
  1. Assign it to a variable:

const title = <h1 className="title">Supermarket</h1>;

  1. Return it from a function

function getTitle() {
return <h1 className="title">Supermarket</h1>
}

  1. Conditionally return different elements:

function getTitle(is_open) {
if (is_open) {
return <h1 className="title">Supermarket</h1>
} else {
return <h1 className="title">Supermarket (closed)</h1>
}
}

  1. Other things you can normally do. It’s a call to React.createElement(…).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is an expression?

A

An expression is any valid JavaScript code that resolves to a value.
This means it’s any JavaScript code that has an end result, for example:

3 + 4
“Sam”
new Date()
2 * 4
name (assuming the variable name has been declared).
And the list goes on.

Every one of these expressions resolves to a value, for example:

3 + 4 resolve to the number 7.
“Sam” resolves to string “Sam”.
new Date() resolves to a date object.
2 * 4 resolves to the number 8.
name resolves to the value of that variable, which will most likely be a string.

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

How do you present expressions in JSX?

A

Wrap them in {}

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

How do you wrap if
a. the value is a string
b. the value is dynamic?

A

a. Wrap it with quotes
b. Wrap it with curly braces

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

How should number and boolean attribute values be passed?

A

Number and boolean attribute values should be passed as an expression:

<input max={2} disabled={true} className=”textbox” />

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

What do you do when an attribute is partly-dynamic?

Eg:
< li id=”item-1” ></li>
< li id=”item-2” ></li>
< li id=”item-3” ></li>

A
  1. Using string concatenation:
    < li id={“item-“ + count} ></li>
  2. or even better, using template strings:
    < li id={item-${count}} ></li>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

How would you prevent the following code from breaking?

function getList() {
return
<ul>
<li>First Item</li>
<li>Second Item</li>
</ul>;
}

A

Wrap it in () because of a JavaScript concept called Automatic Semi-colon Insertion (ASI).

function getList() {
return (
<ul>
<li>First Item</li>
<li>Second Item</li>
</ul>;
)
}

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

Why do you have to wraps your elements you want to return using <></> fragments?

A

Because when returning elements in JSX, you can only return one element at a time.
That element can have children, but you must ensure that you’re only returning one element at a time, or else you will get a syntax error.

That’s because every Element is an object, and you cannot return two or more objects next to each other.

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

Why is it better to wrap elements with <></> instead of <div></div>?

A

The <div> will end up being rendered in your final HTML, whereas fragment tags will disappear (the content of the fragment will be rendered).

Let’s say you’ve got approximately 100 React components. In that case, wrapping each component with an unnecessary <div> would make things slower as the size of the DOM would increase.

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

What is a React Component?

A

Short definition
A React Component is a function that returns one React Element, which describes how a section of the User Interface should look.

Longer definition
A React Component is a function that returns one React Element (result of React.createElement). That returned Element can have many children as we’ve seen in the previous chapter.
The Component allows you to split your UI into independent, reusable pieces.
This lets you think about each piece of your UI in isolation, making it easier to debug.
A React Component is a template or a blueprint that lets you describe a section of the UI; for example, <Footer></Footer> is a React Component that describes the footer.

Components promote code reuse.

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

Why is the following called a ‘function component’?

import {createRoot} from “react-dom/client”;

function Footer() {
return (
<div>
<h3>Company name</h3>
<p>All rights reserved</p>
</div>
);
}

const root = document.querySelector(“#root”);

createRoot(root).render(<Footer></Footer>);

A

We call this a function component because the Component is defined as a function.

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

How does React know that it’s looking at a Component rather than an Element?

A
  1. React checks the first character of this Component, which is F (from Footer).
  2. Is it an uppercase letter? Then it’s a Component.
  3. Is it a lowercase letter? Then it’s an Element.

From the documentation: The first part of a JSX tag determines the type of the React element. Capitalized types indicate that the JSX tag is referring to a React component.
Because React treats components starting with lowercase letters as DOM tags, <footer> would NOT work in this case; it will render the HTML5 <footer> element rather than your own Component Footer.

In summary: A React Component is a function that returns a React Element.

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

Why does the following code cause an infinite loop?

function Button() {
// Be careful: this is an infinite loop
return < Button ></Button>;
}

A

That’s because the < Button ></Button> JSX will be converted to React.createElement(Button) calls which will eventually call the Button function. So you’d end up with a function Button that keeps calling itself repeatedly.

In this case, we probably meant to return <button></button> (lower case) which is the HTML Element button rather than the component Button.

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

Why should you name your exports?

A

This will help you debug your code as you will be able to see the component name when something breaks inside of it, rather than seeing error in anonymous function.

//Footer.js
// this is NOT recommended
export default function () {
return (
<h3>Footer</h3>
);
}

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

What does the following JSX code get transformed into:

< GreetUser user=”Sam” id=”2” />

A

React.createElement(GreetUser, {user: “Sam”, id: “2”});

Notice how the JSX attributes on Components get converted into props as the second argument of React.createElement.

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

What are props? Why are the useful?

A

Props is an object received as the first argument of a Component. Attributes on Components get converted into an object called Props. Props make components more reusable.

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

What does props.children represent?

A

props.children represents the content between the tags of a Component. It can be an array or a single item. It can contain text and/or React Elements and/or React Components. In the example below, Login is the children.

createRoot(root).render(<button>Login</button>);

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

What is status doing in the following deconstructed object?

const {firstName, lastName, status = ‘single’} = person;

A

It is defaulting to “single” because status does not exist on the person object.

39
Q

What should React components never do?

A

Modify their props.

39
Q

What should React components never do?

A

Modify their props. This means that you should never change the value of the prop inside the component; let’s see an example:

function Notifications(props) {
// ❌ do NOT do this (this is changing the props)
props.data.count = props.data.count - 1;
return <h3>You have {props.data.count} unread notifications.</h3>;
}

const notifications = {
count: 3
};

const element = <Notifications data={notifications} />;
console.log(notifications); // {count: 2}

Instead, it should have been written like so:

function Notifications(props) {
// ☑️ this is okay because we’re not changing the props
const value = props.data.count - 1;
return <h3>You have {value} unread notifications.</h3>;
}

const notifications = {
count: 3
};

const element = <Notifications data={notifications} />;
console.log(notifications); // {count: 3}

So you should think of props as read-only.

40
Q

Why should you never modify props?

A

React requires that because then your functions are pure, which means that given the same input (props), they will always have the same result (output).

This allows React to quickly identify which Components need to re-render when a certain prop updates. This happens as part of the Virtual DOM.

41
Q

What is clsx and how do you use it?

A

clsx is a tiny utility for constructing className strings conditionally. clsx({“your-class-name”: booleanValue}) is the generic syntax for clsx.

import clsx from “clsx”;

function MyComponent(props) {
const className = clsx({“title”: props.loggedIn});
return <h1 className={className}></h1>
}

const example1 = <MyComponent loggedIn={true} />; // className=”title”
const example2 = <MyComponent loggedIn={false} />; // className=””

42
Q

How do you create a new object that contains all the keys and values except the id?

const person = {
id: 1,
name: “Sam”,
age: 23,
}

A

const {id, …rest} = person;
console.log(id); //1
console.log(rest); //{name: “Sam”, age: 23}

43
Q

How do you create a new object that contains all the keys and values except the id?

const person = {
id: 1,
name: “Sam”,
age: 23,
}

A

const {id, …rest} = person;
console.log(id); //1
console.log(rest); //{name: “Sam”, age: 23}

44
Q

Why would you spread attributes in JSX?

< h1 tabIndex=”2” className=”navbar” >Hello World< /h1 >

A

Spreading attributes in JSX allows you to take all the props (or a portion of the props) and pass them down to the element being rendered without having to write all the props one by one.

function Navbar(props) {
const {children, …rest} = props;
return <h1 {…rest}>{children}</h1>;
}

45
Q

How might you destructure the following:

const data = [“Sam”, 23, {
id: 1,
created_at: “Jan 19”
}];

A

const [name, age, details] = data;

46
Q

What is State?

A

State refers to any variable defined inside a Component with the intent to update later.

For example: when creating a <Stopwatch></Stopwatch> component, we need to keep track of the seconds elapsed. The seconds elapsed cannot be a props for 2 reasons:

It should be contained inside the <Stopwatch></Stopwatch> rather than passed from outside
It should update/change! Props are supposed to be pure and should not be updated/changed.
If you’re wondering what we mean by “it should be contained inside the Component rather than passed from outside”, remember that props are passed from outside, for example:

< Stopwatch theme=”dark” / >
The theme is a prop because it’s passed from outside.
The theme cannot be changed from within the Stopwatch component; it has to change from the outside. Once it’s changed from the outside, it gets processed again by the component.

This is why theme is a prop. We don’t plan on updating it from inside the Stopwatch.

Whereas the seconds elapsed is a state because we plan on starting it/stopping it from inside the <Stopwatch></Stopwatch> component.

47
Q

What happens when the state changes?

A

When the state is updated, ReactDOM will efficiently and automatically re-render the Component to the DOM. We’ll see how this works soon.

48
Q

Why do we write the combined import like this:

import React, {useState} from “react”;

A
  • React is a default export (no curly braces)
  • useState is a named export (wrapped in curly braces)
49
Q

What does the React hook useState do?

A

useState is a function from the “react” package. It allows us to create a state variable in a Component. useState is a React Hook that hooks into the internals of React and notifies it that a state variable has changed.

50
Q

What does useState return?

A

useState returns an array of 2 items:

  • the first one is the current value of the state
  • the second one is a function that updates the state (this will be explained later)
    So instead of writing:

const result = useState(0)
const seconds = result[0];
const setSeconds = result[1];
We will use the array destructuring syntax:

const [seconds, setSeconds] = useState(0);

51
Q

What happens when you change the state?

A

React will call the Component function again to re-render. The initialValue passed to useState(initialValue) is only used the first time a Component renders.

52
Q

Why is updating state an advantage compared to vanilla JS?

A

Typically with Vanilla JavaScript (JavaScript without any library), you’d have to manually update the DOM every time a variable changes, and that could quickly become messy as the requirements get more advanced.

53
Q

When should you add onClick to a DOM element?

A

You should only add it to the <button> element for accessibility reasons.
Accessibility is the practice of making your website accessible (usable) to all kinds of users regardless of abilities.</button>

For example, some of your users may be using a Screen Reader to access your website. If you add an onClick to elements other than the button, they may not be able to click on those elements.

54
Q

Why move from inline to named event handlers?

A

Moving from inline to named event handlers allows for more complexity inside the event handler.

Eg: < button onClick={handleLoginClick} >Login</button> (< button onClick={() => console.log(“Button clicked”)} >Add 1</button>) calls the handleLoginClick when the button is clicked.

This will help us do the following:

import {useState} from “React”;

function Stopwatch() {
const [seconds, setSeconds] = useState(0);

function handleIncrementClick() {
    setSeconds(seconds + 1);
}

return (<>
    < h2 >{seconds}</h2>
    < button onClick={handleIncrementClick} >Click to add 1</button>
</>); }
55
Q

Why should event handlers be defined inside the component?

A

When event handlers are defined inside the Component, they can use the state variables because of the closures concept.

55
Q

Why should event handlers be defined inside the component?

A

When event handlers are defined inside the Component, they can use the state variables because of the closures concept.

56
Q

What is immutability?

A

An immutable object is an object that cannot be changed. Every update creates a new value, leaving the old one untouched.

57
Q

How do we add an item to an array in an immutable way?

A

We can’t use .push() because push will mutate the array.

Instead, we have to make a shallow copy and then insert the new item in a new array. Here’s what it looks like:

const numbers = [1, 2, 3];
const result = […numbers, 4];
console.log(result); //[1, 2 ,3 ,4]

We spread the values of the numbers array and add 4 afterward. The new array will contain 1, 2, 3, 4.

This is immutable because we are NOT changing the numbers array but rather creating a new copy with the extra number in it.

58
Q

What’s the difference between slice and splice in React?

A

Slice is immutable and helps you remove items from an array in an immutable way, but splice is mutable.

59
Q

What’s the easiest way to immutably remove an item from an array?

A

Filter

const grades = [10, 8, 9, 4, 16];

// return all grades >= 10
const subset1 = grades.filter(grade => grade >= 10);
console.log(subset1); // [10, 16]

// remove the 2nd grade
const subset2 = grades.filter(grade => grade !== 8);
console.log(subset2); // [10, 9, 4, 16]

60
Q

What do you need to provide every time you have a map in JSX?

A

Every time you have a map in JSX, you need to provide a key or else you will get a warning (for performance reasons):

function Grades() {
const grades = [8, 18, 10, 10];

return <ul>{
    grades.map((grade, index) => <li key={index}>{grade}</li>)
}</ul>; }

The key should be a unique representation of the single item inside the map. However, because the grades are not necessarily unique, we can use the index provided by the .map method.

61
Q

Why do we need a key?

A

Using the example below, when one of the items of the array changes, React needs to know which li to update; thus, it requires a unique key so that it can only update that item without having to remove all the lis and render them again.

The same applies to items that need to be added or removed.

function Users() {
// collection of user ids
const users = [1, 10, 3, 4, 13];

return <ul>{
    users.map(user => <li key={user}>{user}</li>)
}</ul>; }
62
Q

What are the differences between Virtual DOM and ‘real’ DOM?

A

Virtual DOM:

  • Can’t directly update HTML
  • Acts as a copy of the real DOM, which can be frequently manipulated and updated without a page refresh
  • More of a pattern than a specific technology
  • Synced with the real DOM with ‘react-dom’

‘Real’ DOM:

  • Directly updates and manipulates HTML
  • Creates a new DOM / full repaint if it is updated
  • An object-based representation of an HTML document and an interface for manipulating that object
63
Q

What’s the key difference between Virtual DOM and ‘real’ DOM?

A

Diffing. Virtual DOM looks at the difference between one state and the next state in the DOM and says what has to be changed. It then just changes that individual part of the DOM rather than the entire page itself.

64
Q

Are Virtual DOM and Shadow DOM the same?

A

No, Shadow DOM is a separate browser-specific technology. Virtual DOM is a pattern built into React, Angular, Vue, etc.

65
Q

How do you remove the last item from an array immutably?

A

function handleUndoClick() {
setTransactions(transactions => transactions.slice(0, transactions.length - 1))
}

66
Q

How can you immutably change age from 19 to 20 in the following object?

const data = {
id: 1,
age: 19
}

A

const data = {
id: 1,
age: 19
}

// GOOD: immutable
const newObj = {…data, age: 20};

console.log(newObj); // {id: 1, age: 20}

console.log(data); // original object did not change {id: 1, age: 19}

67
Q

How do you immutably remove a key/value pair?

A

By destructuring the object, together with the spread operator.

const obj = {
id: 1,
title: “Harry potter”,
year: 2017,
rating: 4.5
}

// GOOD: immutable
const {year, …rest} = obj;
console.log(rest); // { id: 1, title: “Harry potter”, rating: 4.5}

68
Q

How do you loop through an object in JSX?

A

function App() {
const settings = {
title: “Blog”,
theme: “dark”
}

return <ul>{
    Object.entries(settings).map(item => {
        return <li key={item[0]}>{item[0]} with value {item[1]}</li>
    })
}</ul>; } The resulting JSX will be:

<ul>
<li>title with value Blog</li>
<li>theme with value dark</li>
</ul>

This works because Object.entries(settings) returns an array that looks like this:

[
[“title”, “Blog”],
[“theme”, “dark”],
]

69
Q

How do you get the text written by the user on a form?

A

onChange event handler. In the example below, handleAddressChange function will be called every time the user enters a new character, removes one, or makes any edit to the textbox. It will fire every time the input changes.

function handleAddressChange(event) {
//…
}

<input type=”text” name=”address” onChange={handleAddressChange} />

70
Q

What’s the difference between target and currentTarget in React?

A

When it comes to React’s onChange, there is no difference between target and currentTarget because there’s only one element with no children. So, both values will resolve to the same element.
You will see developers using target, which we also recommend.

71
Q

How can you read the text a user enters?

A

You can read the user’s text with event.target.value.

72
Q
  1. What is a controlled component?
  2. Why is it useful?
  3. How do you create one?
A
  1. A controlled component is when you keep track of an input’s value as state and update it whenever it changes.
  2. This is useful almost every time you have an <input></input> (or even a <select></select> or <textarea></textarea> elements) as it lets you get the value written by the user as well as automatically change its value when the state changes.
  3. Here’s how you create a controlled component:

a. We start by creating a state variable to store the value

b. This state will have a default value of an empty string “”

c. We set the value of the input to that state variable

d. We update the state every time it changes

import {useState} from “react”;

function App() {
const [address, setAddress] = useState(“”);

return <input type="text" value={address} onChange={event => setAddress(event.target.value)} />; }

Let’s re-iterate over the steps:

a. We start by creating the address state

b. We give it a default value of “”

c. We set the <input></input>’s value={address}

d. We update the state every time it changes: onChange={event => setAddress(event.target.value)}

73
Q

How do you prevent the form from submitting so that you can send the data with fetch?

A

event.preventDefault()

function App() {

function handleFormSubmit(event) {
    event.preventDefault();
}

return <form onSubmit={handleFormSubmit}>
    <input type="text" name="name" />
    <input type="submit" value="Add" />
</form>; }

(Note that we preferred a named function definition over an inline function because eventually, we will have several lines of codes, not just the event.preventDefault().)

74
Q

How do you add a label to an input in React?

A

A <label></label> needs an htmlFor attribute that points to the id of the element.

<form>
<label>Email: </label>
<input></input>

<label>Password: </label>
<input></input>

<input></input>
</form>

75
Q
  1. What is a shallow copy?
  2. What is a deep copy?
A
  1. A shallow copy means that it creates a new array, but the objects are still referring to the old ones. Hence changing an object in the new array will also change in the old one because they’re pointing to the same object.
  2. A deep copy means that the new array contains new objects, so changes to those new objects will not affect the old ones in the original array.
76
Q

What’s the difference between stateful and stateless components?

A

React Components can either be stateless or stateful.
The distinction is with regard to whether the component handles state or not.

Stateless components do NOT manage state internally. So you will not find useState calls inside of them. On the other hand, stateful components will manage at least one state variable.

77
Q

Can stateless components be interactive?

A

Even though stateless components do not manage state internally, they can still be interactive.

For example, a stateless component can contain a form as well as a textbox and a submit button. However, the state will be managed by its parent component.

This is the first concept that we will be covering in this chapter.

To make that possible, we first must realize that props can also pass functions.

78
Q

What’s the naming convention for props that are functions?

A

Start them with onSubjectEvent.

function App() {
function handleStoreOpen() {

}

function handleItemClick() {

}

return <StoreFront
        onStoreOpen={handleStoreOpen}
        onItemClick={handleItemClick}
    /> }
79
Q

How can a component pass a function to a child component?

A

A component can pass a function to a child component as a prop.

80
Q

What are two benefits of having all the shared state in the closest common ancestor component?

A
  • The common ancestor becomes the single source of truth. This makes it substantially easier to find bugs and fix them, as you know that there’s only one place where this state will be changed.
  • Having this centralised location for the state, makes it easier to maintain consistency in your application. If you create some validation logic for the entry, you will only have to do so once in the common ancestor.
81
Q

Why do we want to lift the state up?

A

We lift the state up because we want the data to flow down.

When the data flows down, your app becomes more predictable, and finding and isolating bugs becomes easier.

82
Q

What are the benefits of breaking up a component into smaller ones? What’s the name of this process?

A

This process is called abstraction.

  • Reusability: You can reuse the smaller components anywhere in your application if you need to.
  • Isolate bugs: If you found a bug with a part of your UI, you will be able to isolate it to 1 or 2 small components rather than one huge component.
83
Q

What are the factors for breaking up a component?

A
  • Need for reusability
  • The component becomes “too complicated”.
  • Expecting further development
84
Q

Why does counter in the code below turn to one instead of two on one click?

import {useState} from “react”;

function App() {
const [counter, setCounter] = useState(0);

function handleButtonClick() {
    setCounter(counter + 1);
    setCounter(counter + 1);
}

return <button onClick={handleButtonClick}>Click me {counter}</button> }
A

These 2 state updates will be batched together, and having counter = 0, the first setCounter() call set the counter to 0 + 1 = 1, but not immediately because it’s asynchronous.

Then we have the following call setCounter(counter + 1), but the value of counter is still 0 because the component did not re-render yet.

So the second call will also set the state to 1.

A reminder that this is caused because the state updates are batched.

85
Q

How would you change the following code so counter = 2 after one click, and not counter = 1?

A

React has the concept of functional state updates which is when you pass a function to the state update function. This will add 2 every time you click on the button.

import {useState} from “react”;

function App() {
const [counter, setCounter] = useState(0);

function handleButtonClick() {
    setCounter(counter + 1);
    setCounter(counter + 1);
}

return <button onClick={handleButtonClick}>Click me {counter}</button> }
86
Q

When should you use functional state updates?

A

Whenever the new state is computed using the previous state, then you should use functional state updates to guarantee consistency and prevent unexpected bugs.

So, if you’re incrementing a counter, you should use a functional state update. On the other hand, if you’re resetting a counter back to 0, you don’t necessarily have to use a functional state update (as the new value is not computed using the previous state).

87
Q

What are some examples of effects? Why are they called effects?

A
  • Send a request to your analytics provider
  • Initialize a DOM plugin outside of React (for example, drawing a map; we’ll see that in the following Project)
  • Change the page title (the one that shows up in the browser tab)
  • Subscribe a user to a live chat service (with WebSockets)

They are called effects because they are instructions running outside your component or as a result of your component.

88
Q

Why are effects needed?

A

Effects are needed when you need to synchronize React with any external API. For example, changing the page title is considered an external API as it’s not managed by React.

When you call useEffect, you’re telling React that your component needs to do something after every render.

89
Q
A
89
Q

What does React Strict Mode do?

A

<React.StrictMode></React.StrictMode>

helps you find unwanted bugs when React is running in development mode. React strict mode has no effect in production mode.

89
Q

Why do we need a useEffect hook?

A

One of the main reasons is performance. Your components should be very fast to render, allowing your app to keep re-rendering very fast.

Also, the code you have before the return statement runs before the JSX is produced from your component. On the other hand, code inside the useEffect hook runs only after your component has rendered to the DOM.

90
Q
A