Chapter 2: Single Page Applications

Last time...
19:29

  • React allows UI to be created declaratively: this avoids having to deal with DOM mutations and enables a programming model where conceptually everything is created from scratch while maintaining performance.
  • Components allow reuse, composition and encapsulation
  • In React, components are just functions that return JSX
  • Components are rerendered at every state/prop change
  • useState: create a state variable with a setter that triggers the UI to rerender
  • useEffect(callback, [...dependencies]): callback is only run when one of the dependencies change

Single Page Applications
19:29

Definition

A single page application (SPA) is a website that interacts with the user by dynamically mutating the current page instead of loading entire new pages. The goal is faster transitions.

React (and Angular, Svelte, Vue, etc.) make SPA easy to write because we don't have to deal with mutations.

Question

Why are we doing this? Can you think of any features that only work with SPA?

Two key ingredients: fetch and Client-Side routing.

Client-Side routing
19:29

Remark

Using single page, we'd lose key functionalities like:

  • Restoring the correct page on reload
  • Sharing a link to the current state of the application
  • History
  • Back and forward navigation

These issues can all be solved with Client-Side Routing

Idea (Client-Side Routing)

  • Redirect all URLs to the SPA
  • Use window.location.href to choose what to display on the page.
  • Changing "page" uses the history.pushState API

React Router will handle all of this for you.

React router tutorial
19:29

Instruction

Follow the tutorial

Exercise: timetable
19:29

Exercise

Create a Google Calendar clone that shows your timetable (use the link to your ICS file). You might find libraries such as MUI and FullCalendar useful.

Your app should use React Router.

Tips
19:29

Here are some tips for better DX

  • Use prettier
  • Use eslint
  • Use TypeScript in strict mode
  • Your components should be small
  • Break down your code into ES modules, and organise them well into folders
  • Use unplugin-auto-import to avoid repetitive import statements

A modern implementation of useEffect/useState
19:29

We will implement a Signal-based version of React's hooks. Formally, It will be different in at least two aspects (under the hood, it's as different as can be).

  • In the instruction
    state is a function.
  • We won't need to specify the dependencies array

Idea

  • Effects are kept on a stack (FILO)
  • For each state variable, register all the effects that depend on it
  • When calling the setter, trigger all the effects

Solution
19:29