React Tutorial Flashcards
What is React?
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.
What’s the difference between a framework and a library? Which is React?
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.
Why must we import React?
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.
What’s the difference between a method and a property?
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”
What’s the cost of importing React?
The cost of importing React is approximately 6KB.
Why do we use className and not class when changing an element’s class in React?
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).
What’s the difference between document.createElement and React.createElement?
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: {}
}
Why does React.createElement return an object rather than the DOM element itself?
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).
What is a React Element?
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>).
What are the three parameters in React.createElement?
React.createElement(type, options, children)
Eg: React.createElement(‘h1’, {className: ‘hero-title’}, ‘Welcome to our supermarket’)
What is the ReactDOM?
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.
Why is it a separate library?
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).
What is Reconciliation?
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 do you install React and ReactDOM?
npm install react react-dom
How much does ReactDOM weigh?
130kb
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?
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 can we render our React Element?
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:
- We start by getting a reference to the root element from the page (using querySelector or getElementById).
- We create the root of the React app using createRoot(root).
- On the result of createRoot(root), we call .render() and pass to it our React element.
Why do we use JSX?
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.
What does the following get translated to?
import React from “react”;
const title = <h1>Hello World</h1>
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.
Is JSX part of the browser?
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).
Since you can essentially think of a JSX element as if it were an object, what can you do with it?
- Assign it to a variable:
const title = <h1 className="title">Supermarket</h1>;
- Return it from a function
function getTitle() {
return <h1 className="title">Supermarket</h1>
}
- 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>
}
}
- Other things you can normally do. It’s a call to React.createElement(…).
What is an expression?
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 do you present expressions in JSX?
Wrap them in {}
How do you wrap if
a. the value is a string
b. the value is dynamic?
a. Wrap it with quotes
b. Wrap it with curly braces
How should number and boolean attribute values be passed?
Number and boolean attribute values should be passed as an expression:
<input max={2} disabled={true} className=”textbox” />
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>
- Using string concatenation:
< li id={“item-“ + count} ></li> - or even better, using template strings:
< li id={item-${count}
} ></li>
How would you prevent the following code from breaking?
function getList() {
return
<ul>
<li>First Item</li>
<li>Second Item</li>
</ul>;
}
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>;
)
}
Why do you have to wraps your elements you want to return using <></> fragments?
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.
Why is it better to wrap elements with <></> instead of <div></div>?
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.
What is a React Component?
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.
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>);
We call this a function component because the Component is defined as a function.
How does React know that it’s looking at a Component rather than an Element?
- React checks the first character of this Component, which is F (from Footer).
- Is it an uppercase letter? Then it’s a Component.
- 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.
Why does the following code cause an infinite loop?
function Button() {
// Be careful: this is an infinite loop
return < Button ></Button>;
}
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.
Why should you name your exports?
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>
);
}
What does the following JSX code get transformed into:
< GreetUser user=”Sam” id=”2” />
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.
What are props? Why are the useful?
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.
What does props.children represent?
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>);