4IT580: Docs
4IT580 WebGithub

2nd Theoretical Class:
Introduction to React




Useful links

React

Why?

Example

Below, there is current time and an input field rendered using a single React component.

Right-click the current time and inspect the element to see that only the time gets updated in the DOM. React is smart!

Components

A React application is usually composed of multiple components.

Here is a sample blog application and what its component hierarchy can look like:

Advantages of components

What is a component in React code?

It is a function!

A function that returns JSX markup.

It is a snapshot of the UI in time.

React renders a component by calling the function.

Displaying a React app in the browser

Usually, you only need to run this code once at startup. It will:

📄 index.js

📄 index.html

Resulting HTML:

JSX

Allows us to write HTML code in React (JavaScript code) - mix JavaScript with HTML.

Custom components start everytime with a capital letter!

JSX is just a syntactic sugar which is calling JavaScript functions for creating React elements under the hood.

That's why is not HTML - JSX has stricter rules and some differences.

JavaScript in JSX

In JSX returned from a function (component), we can use JavaScript properties, functions, etc. Pass JavaScript code into {} in JSX template.

Props

Special props

Events

Execute JavaScript code (function, ...) when a user interacts with the application:

...and many more.

Hint: When passing an event handler stored in a constant, make sure not to call it immediately - only pass the reference to it!

React will make sure to call the function at the right time when you click the button.

Hooks

Special React functions allowing you to store internal state, run side effects and more things inside a component.

Hooks always start with use.

React has several built-in hooks.

Component lifecycle

A component can be rendered many times during its life.

useState

A hook which allows us to keep track of an internal state inside a component.

The state will be kept during its lifetime until the component is unmounted.

By calling the setState function with a new value:

useEffect

Effects let you run some code after rendering so that you can synchronize your component with some system outside of React.

Executing a side effect

Something needs to be changed from outside - for example an API call.

When a component is mounted, we need to fetch data.

Specifying when to execute an effect

You can control when the effect runs via the dependencies argument and/or returning a function.

Modern JavaScript

Import & Export

We have 2 types of exports.

Named exports

Default exports

var vs const & let

Don't use var! Use let only if neccesary! => Use const!

Template string

We have several ways how to work with strings

Destructuring