---
# System prepended metadata

title: 5.1. Intro to React

---

# 5.1. Intro to React

## Leaning goals

- Understand why we use React
- Understand what React is and what React does for us

React concepts:

- The virtual DOM
- JSX
- Components
- Props & State
- Handling Events

## Vocabulary

- **framework** - A software framework provides a standard way to build and deploy applications. It is a universal, reusable software environment that provides particular functionality as part of a larger software platform to facilitate development of software applications, products and solutions
- **Virtual DOM** - An in-memory object that represents a DOM structure and can be manipulated with JavaScript before updating the real DOM
- **JSX** - A mix of JavaScript and XML that facilitates rendering the appropriate HTML Components: standalone, independent parts of an application that are responsible for handling only a single UI element
- **Components** - Components are standalone, independent parts of an application that are responsible for handling only a single UI element
- **Functional components** - Functional Components are components that simply need to render content to the DOM, and do not need to be aware of any application data that might be changing
- **Class Components** - Class components are ES6 classes that extend an abstract 'Component' class, given to us by default by React. They typicall keep track of some sort of application data
- **Props** - This is shorthand for properties. Props is an object that is given from it's parent component down to the child functional/class component. Props should remain immutable
- **State** - State holds data that represents the actual state of an application. State can be changed and mutated through user interactions

## What is React?

_React is a client-side JavaScript framework that allows you to easily and efficiently manipulate the DOM based on application data and how it changes in response to user interaction._

**What is application data?** - Think about all the content you see on a site like Facebook - user profiles, their posts, comments on those posts, etc. All of this is considered application data. One of the core differences between building a web site and building a web app is that web apps have to manage a large amount of data that can be manipulated by its users. For example, Facebook users can add and delete posts, edit comments, change their profile information, etc. A web application has to store and maintain all of this data even as it updates based on user interaction.

React allows us to ensure our application UI is displaying all the correct information at any given time, no matter how frequently it changes.

React give us:

- **The Virtual DOM** - an in-memory object that represents a DOM structure and can be manipulated with JavaScript before updating the real DOM
- **JSX** - a mix of JavaScript and [XML](https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction) (Extensible Markup Language) that facilitates rendering the appropriate HTML
- **Components** - standalone, independent parts of an application that are responsible for handling only a single UI element
- **Props & State** - objects in React where we can store application data and other values that will affect the rendering of our components

## Why React?

Think about how you’ve previously interacted with the DOM, without the help of a framework. You maybe used vanilla JavaScript to manipulate text or class names based on event listeners applied to certain selectors.

Standard methods of DOM manipulation are tedious, slow and fragile. It requires us to manually target elements, it takes a long time for the browser to process DOM manipulations, and the amount of code it requires makes it really fragile. There are too many places where we could go wrong with a simple typo.

A big benefit of React is how well it can handle DOM manipulations in an easy way and efficient way. This is done through the use of a Virtual DOM.

## The virtual DOM

A Virtual DOM is a JavaScript object that represents a copy of a DOM structure. This provides us with a huge performance benefit, because accessing and updating a JavaScript object is much faster than accessing the true DOM directly.

React lets us alter this virtual DOM first, then renders the change for us - making the smallest amount of true DOM manipulations possible. React will only render the differences of what actually needs to be changed, rather than making a massive DOM manipulation to elements on the page that aren’t actually changing.

This idea of a Virtual DOM isn’t unique to React. It’s found in many other client-side frameworks.

## JSX

JSX produces React “elements”. It is a syntax extension to JavaScrip to describe what the UI should look like.

**Embedding Expressions in JSX**

You can put any valid [JavaScript expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Expressions) inside the curly braces in JSX:

```javascript
const name = "Cheetah";
const element = <h1>Hello, {name}</h1>;

ReactDOM.render(element, document.getElementById("root"));
```

Another example:

```javascript
function formatName(user) {
  return user.firstName + " " + user.lastName;
}

const user = {
  firstName: "Harper",
  lastName: "Perez",
};

const element = <h1>Hello, {formatName(user)}!</h1>;

ReactDOM.render(element, document.getElementById("root"));
```

**JSX is an expression too**

This means that you can assign it to variables, or return it from functions:

```javascript
function getGreeting(user) {
  if (user) {
    return <h1>Hello, {formatName(user)}!</h1>;
  }
  return <h1>Hello, Stranger.</h1>;
}
```

**Attributes**

Since JSX is closer to JavaScript than to HTML, React DOM uses camelCase property naming convention instead of HTML attribute names.

For example, class becomes `className` in JSX, and tabindex becomes `tabIndex`.

```javascript
const element1 = <div tabIndex="0"></div>;
const element2 = <img src={user.avatarUrl}></img>;
```

> Note: Don’t put quotes around curly braces when embedding a JavaScript expression in an attribute.

## Components and Props

Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.

The simplest way to define a component is to write a JavaScript function:

```javascript
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
```

This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element. We call such components “function components” because they are literally JavaScript functions.

You can also use an ES6 class to define a component:

```javascript
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
```

The above two components are equivalent from React’s point of view.

> **Note: Always start component names with a capital letter.**
>
> React treats components starting with lowercase letters as DOM tags. For example, `<div />` represents an HTML div tag, but `<Welcome />` represents a component and requires `Welcome` to be in scope.

### Rendering a Component

For example, this code renders “Hello, Sara” on the page:

```javascript
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;
ReactDOM.render(element, document.getElementById("root"));
```

What happens in this example:

1.  We call `ReactDOM.render()` with the `<Welcome name="Sara" />` element.
2.  React calls the `Welcome` component with `{name: 'Sara'}` as the props.
3.  Our `Welcome` component returns a `<h1>Hello, Sara</h1>` element as the result.
4.  React DOM efficiently updates the DOM to match `<h1>Hello, Sara</h1>`.

Components can refer to other components in their output. This lets us use the same component abstraction for any level of detail. A button, a form, a dialog, a screen: in React apps, all those are commonly expressed as components.

For example, we can create an App component that renders Welcome many times:

```javascript
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
```

### Props are Read-Only

**The component must never modify its own props.**

Consider this `sum` function:

```javascript
function sum(a, b) {
  return a + b;
}
```

Such functions are called **pure** because they do not attempt to change their inputs, and always return the same result for the same inputs.

In contrast, this function is impure because it changes its own input:

```javascript
function withdraw(account, amount) {
  account.total -= amount;
}
```

React is pretty flexible but it has a single strict rule:

**All React components must act like pure functions with respect to their props.**

Of course, application UIs are dynamic and change over time. In the next section, we will introduce a new concept of "state". **State** allows React components to change their output over time in response to user actions, network responses, and anything else, without violating this rule.

## State

`State` is slightly different than `props`: `state` holds data that represents the actual state of our application. State can be changed and mutated through user interactions, whereas props should remain immutable.

Props and state are related. The state of one component will often become the props of a child component. Props are passed to the child using tag attributes:

```javascript
<MyChild name={mystate} />
```

There are three things you should keep in mind when use state:

- **Do Not Modify State Directly**
- **State Updates May Be Asynchronous**: React may batch multiple `setState()` calls into a single update for performance.
- **State Updates are Merged**: When you call `setState()`, React merges the object you provide into the current state.

## Handling Events

Handling events with React elements is very similar to handling events on DOM elements. There are some syntax differences:

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

For example, the HTML:

```html
<button onclick="activateLasers()">Activate Lasers</button>
```

is slightly different in React:

```javascript
<button onClick={activateLasers}>Activate Lasers</button>
```

When using React, you generally don’t need to call `addEventListener` to add listeners to a DOM element after it is created. Instead, just provide a listener when the element is initially rendered.

**Passing Arguments to Event Handlers**

Inside a loop, it is common to want to pass an extra parameter to an event handler.

```javascript
<button onClick={(e) => deleteRow(id, e)}>Delete Row</button>
```

The `e` argument representing the React event will be passed as a second argument after the ID.

## Additional resources

- [ReactJS Docs](https://reactjs.org/)
- [React DevTools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en)
- [Props vs. State](https://stackoverflow.com/questions/27991366/what-is-the-difference-between-state-and-props-in-react)
