---
# System prepended metadata

title: '2104-GHP-NY-WEB-FT: Week 3 Notes'

---

# 2104-GHP-NY-WEB-FT: Week 3 Notes

## Webpack

Webpack is something called a "module bundler". The idea is that it packages up JavaScript code to be sent to the frontend.
This enables us to use features like `import/export` (ES modules) in the frontend

The basic anatomy of the `webpack.config.js`

```javascript=
module.exports = {
    mode: "development",
    // Where you want webpack to look and the "entry point" of your client
    entry: "./src/main.js",
    // Where you want the bundle to be outputted
    output: {
      // Generally you will want to put the generated bundle files in the public directory with the static files (CSS, HTML, imgs)
      path: __dirname + "/public",
      // Name of the bundle
      filename: "bundle.js"
    }
}
```

Running `webpack -w` will generate the `bundle.js` file

You will want to include the path to this `bundle.js` inside a script in the HTML. 

Take a look at the [code demo](https://github.com/FullstackAcademy/2104-GHP-webpack)

## Single Page Applications and AJAX

**Note**: *Leverage the Network Tab in the Dev Tools*

Up until this point, we have been actually making Multipage Applications. Take for example, Wikistack. If we wanted to load another page, we would need to go to the server and send back the page we requested. 

Multipage applications query the server for the HTML file we are looking for when switching pages and then refreshes the page entirely. Examples of Multipage applications are:
- Neopets
- Wikipedia

Single Page Application leverages AJAX (asynchronous calls that grab data (usually in JSON format)) to issue requests behind the scenes without reloading and interrupting the user experience. Examples of SPAs are:
- Gmail
- Google Maps

You can use the `fetch` API (built in) or `axios` (need to download) to issue requests to a route (on a server)

### `fetch`

```javascript=
const getDrinks = async() => {
    const fetchDrinks = await fetch('https://www.thecocktaildb.com/api/json/v1/1/random.php')
    const drinksJSON = await fetchDrinks.json()
    console.log(drinksJSON)
}
```

### `axios`

You need to `npm i axios` to use it.

See example [demo](https://github.com/FullstackAcademy/2104-GHP-spa-ajax)

## The Problem: Building User Interfaces is Hard

Why?

Because there is so much stuff to remember as our application gets more and more complex.

## Key concepts: State + View

## Thinking About State: Keeping UI and State In Sync

- Every user interface has data, which we often called state and it presents something based on the data that it is given
- Any change to the data should be reflected in the view

**A one line definition of state:** *Data that changes over time*

## Thought Experiment: Building a To Do List App

### Some Data in the App

- List of to dos
    - Whether a to do is active or completed
- If we have a feature to show all, active or completed to dos
- Number of items left
- Even the text that is entered in the input

[Flask: To Do List Web App](https://flask.io)

### Example State for Our To Do List

```javascript
{
    "todos": [
        {"text": "Write a UI", "status": "completed"},
        {"text": "Bake cookies", "status": "active"},
        {"text": "Take over the world", "status": "active"}
    ],
    "showStatus": "all"
}
```
How do we represent this in the DOM?

### Feature: Add A To Do

**Implementation**

- Push new todo in our "todos" array
- Append a new element to the DOM


### Consideration: What is our UI currently showing?

We've indicated that we have various status that we can show such as the currently active, completed or all the todos

### Assumption: Our UI is currently showing the completed todos and we are trying to add a new, active todo

- Does the "status" of the todo match what we're currently showing
    - Yes: Append a new element to the DOM
    - No: Don't append a new element to the DOM

### Change The State: Switch Back to All To Dos

**Implementation**

- Change the "showStatus" to "all"
- Check our list of "todos" and add any that aren't showing back in
    - Make sure they are in the right order
    - Make sure to change the highlighted from "completed" to "all"

### Takeaway: Remembering to change the view after we change the data is hard

## What if we could just change the data and the view would... React?

![Sunglasses on](https://media.giphy.com/media/58F3GAjnqyW8yBVIsC/giphy.gif)

## React

- Data is called "state"
- When we updated "state", React re-renders the view for us
- React re-renders the view in a performant way

- **Key React Concept**: *"Keeping the state (data) and UI in sync"*
    - This is the purpose of React
- React says, "You give me the data; I'll handle the DOM"

### `setState`

- *Cardinal Rule: We do not mutate state distrectly*
- We use a method called `setState`
    - This is because React can handle things intelligently if multiple updates happen at once

### Key React Concept: JSX

JSX: 
> "Please, don't call me HTML"

JSX is a syntax extension of JavaScript in which it produces React elements. It's HTML-like but not HTML. We can write JavaScript expressions in the HTML-like syntax.

### React Summary

React embraces the fact that rendering logic is inherently coupled with other UI logic (keeping the UI and state in sync): how events are handled, how the state changes over time, and how the data is prepared for display.

Instead of artificially separating *technologies* by putting markup and logic in separate files, React [separates *concerns*](https://en.wikipedia.org/wiki/Separation_of_concerns) with loosely coupled units called “components” that contain both.

### Two Ways to Write a Component

- Class
- Functional


#### Class Component

```javascript
class Pizza extends React.Component {
    render() {
        return <div>Pizza Pie></div>
    }
}
```

#### Functional Component

```javascript
const Pizza = () => {
    return <div>Pizza Pie!</div>
}
```

### Class Components vs. Functional Components

#### Classes

- Defined using `class` keyword
- Maybe stateful (declaring state in a constructor)
- Must have a `render` method
- Access props passed to it via `this` context (i.e., `this.props`)

#### Functionals

- Just a function
- Function's return value is the "render"
- Can have state in the form of React Hooks but we don't learn that until later. As of now, we use functional components as stateless components
- Access props passed to it via the first argument to that function (i.e., If you call it props, then it's `props.`)

### Class Components Are JavaScript Classes and Functional Components are JavaScript Functions

#### Functional Components vs. JavaScript Functions

```javascript=
// Function
const add = (x, y) => {
    return x + y
}
// Call it
add(2, 3)
```

```javascript=
// Functional Component file Add.js
const Add = (props) => {
    return <div>{props.x + props.y}</div>
}

export default Add

// In some other component file called Main.js

import Add from ./Add

const Main = () => {
    // "Call" the add component. We are passing 2 and 3 as props!
    return <Add x={2} y={3} />
}
```

#### Walking through binding `this` with functions declared in React and Class Components vs. JavaScript Classes

Remember: React is like a fancy and extended JavaScript so we have to think about how JavaScript's `this` context works. In your repo, refer to `this` review for more details.

So, let's actually look at what a `class component` looks like:

```javascript=
class SomeComponent extends React.Component {
    constructor() {
        super()
        this.state = {
            someState: 'Some State'
        }
    }
    
    render() { // Render is something we get from React.Component
        <div>{this.state.someState}</div>
    }
}
```

As referenced above, React is fancy and extended JavaScript so above roughly translates to below plain JavaScript class (Note: Below class is extending another class with nothing in it just for demonstration purposes)

```javascript=
class SomeOtherClass {
    someFunction(){...}
}

class SomeClass extends SomeOtherClass {
    constructor() {
        super()
        this.someObject = {
            someStuffInObject: 'Some stuff in object'
        }
    }
    
    someFunction() {
        console.log(this.someObject.someStuffInObject)
    }
}
```

Let's trim the above class a bit to demonstrate the concept of `bind`

```javascript=
class DisplayName {
    constructor(name) {
        this.name = name
    }
    
    display() {
        console.log(this.name)
    }
}
const x = new DisplayName('Noelle')
x.display() // Noelle

// These two lines below simulate a "loss of the `this` context"
// This is synonymous to what we are doing when we do event handling in React
const y = x.display
y() // Uncaught TypeError: Can not ready property name of undefined
```
![](https://i.imgur.com/ekpevTg.png)


So, how do we fix this? By using `.bind` to bind the `this` context to the class


```javascript=
class DisplayName {
    constructor(name) {
        this.name = name
        this.display = this.display.bind(this) // Add this (lol)
    }
    
    display() {
        console.log(this.name)
    }
}

const x = new DisplayName('Noelle')
x.display() // Noelle

// Because we bound the this context to the class, it will refer to name in the class
const y = x.display
y() // Noelle
```

![](https://i.imgur.com/HWMEGeX.png)


### Key Concept: Modularity

As we recall, React lets us write different components. This enforces the idea of modularity to split our frontend up into many different components

### Key Concept: Reusablility

We don't want to get component happy. We definitely want to be modular but we want to be strategically modular. Instead of creating a new component for each topping, we should creating a Toppings component that takes in some argument that indicates what type of topping we are sending it and just reuse this Toppings component as necessary

### Key React Concept: Props

- This is conceptually and syntactically similar to an HTML attribute
- All props that are passed into a component become key-value pairs on that component's "props" object
- React Components have a default props object attached to them that is initially empty until we use it
- We are passing information down from one component to another

```html
<!-- 
    - The `<a>` defines the hyperlink
    - The `href` attribute specifies the URL of the page the link goes to
-->
<a href="http://gph.is/2dsPrSF" />
```

### Key React Concept: Unidirectional Data Flow

- All it means is that we should view our UI as a hierarchy of components
    - We already think of HTML this way
- **The Big Difference**: *Our state is also communicated via this hierarchy*
- Consider props as a game of telephone but instead we are passing information down to components


### Question: Where should we declare state?

### Key React Concept: Declaring state too Low: Lifting State Up

[React Documentation: Lifting State Up](https://reactjs.org/docs/lifting-state-up.html)

> Often, several components need to reflect the same changing data. We recommend lifting the shared state up to their closest common ancestor.

### Key React Concept: Lifting State Too High

We can declare state too high in React and that means we would need to drill through layers of components via props to get state where it needs to be

[Kent C. Dodds: Prop Drilling](https://kentcdodds.com/blog/prop-drilling)

### Concept Battle: State vs. Props

- State is local to a specific component. No other component knows about it unless we pass it down through props.
- Props is a data delivery system where we pass data from one component to another in a hierarchy.
    - Each component has a props object


### Key React Concept: Key Attributes in JSX Elements

[Lists and Keys Documentation](https://reactjs.org/docs/lists-and-keys.html)

> Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity

### Anonymous function inside `onClick`

Why?

Because **we are passing a function to be called eventually** instead of calling the function immediately. **We also want to pass an argument to that function being called.** 

If we passed it like this:

```javascript=
onClick={someFunction('hello')}
```

It would immediately run when the component renders, which we don't want

If I create something like this:

```javascript=
const onClick = alert('Hello')
```

It will run automatically

If I create something like this:

```javascript=
const onClick = () => alert('Hello') // Won't immediately run the alert
console.log(onClick) // This will just log the function definition
console.log(onClick()) // This will call the alert function
```

It won't run immediately and will only run when I do line 3. 

Relating back to the `onClick` attribute, we are only trying to invoke the function when a click happens

- [React Documentation: Why is my function being called every time the component renders?](https://reactjs.org/docs/faq-functions.html#why-is-my-function-being-called-every-time-the-component-renders)
- [React Documentation: How do I pass a parameter to an event handler or callback?](https://reactjs.org/docs/faq-functions.html#why-is-my-function-being-called-every-time-the-component-renders)


### React Lifecycle

* When we render a component, React components go through several different stages in addition to the `render` stage
* React exposes the ability to "hook" into these stages so that we can perform certain actions ourselves (like adding an event listener) (also like Sequelize Hooks)

### When we first start up the app

`ReactDOM.render` -> `render` -> component is mounted -> `componentDidMount`

For a complete list of all the lifecycle methods, here is a [diagram](https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/)

### `ReactDOM.render` vs `render`

#### `ReactDOM.render`

It takes the component (React element) we pass as the first argument and renders it into the "supplied container" from the second argument (div element from index.html)

It renders DOM elements backed by instances of their components

#### `render`

This is when the component's render method is invoked or when the functional component itself is invoked

React compares the JSX ooutput of the render method with its internal virtual DOM and makes a decision about how to update the actual DOM in a performant way

Check out React's documentation on [Reconciliation and their Diffing Algorithm](https://reactjs.org/docs/reconciliation.html)

### Virtual DOM

React's local/internal, simplified copy of the "real" DOM. The idea is that it's much more expensive to manipulate the real DOM, so instead React does a bit of JavaScript first to do less plain DOM Manipulation

### Mounted Component

When the JSX of the component gets turned into live DOM nodes

### `componentDidMount`

* Runs only once after the *initial* rendering
* A good place to fetch initial data from our server
* A good place to attach event listeners

### `componentWillUnmount`

* A good place to clean things up such as timers, intervals, event listeners that we declared that React isn't in control over
    * That `onClick` property on the button? React has control over it so, it has internal mechanisms to clean that up
* This will run when a component is about to be unmounted
    * This generally happens when the elements may have different types such as going from `<button>` to `<div>` or in the case of our example, we just threw an error to break the React app


