React

While Web Components are future-proof, React is currently the most popular JavaScript library for building dynamic and interactive user interfaces.

React primarily does two things: it maps JavaScript state or data to the DOM and efficiently manages component rendering and updates.

ui = f(state)

Basics

Here's a minimal example:

import React from 'react' // why is this necessary?
import ReactDOM from 'react-dom/client'

function HelloWorld() {
  return <div>Hello, world!</div>
}

const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(<HelloWorld />)

How can you mix HTML in JavaScript? That's actually JSX, it is not part of the JavaScript standard and requires transpilation before the browser can parse and execute it.

During the transpilation process, JSX converts into React.createElement() calls, like this:

import React from 'react'
import ReactDOM from 'react-dom/client'

function HelloWorld() {
  return React.createElement('div', null, 'Hello, world!')
}

const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(React.createElement(HelloWorld))

JSX is optional, it's just syntactic sugar. If you're not using JavaScript or TypeScript, you might be utilizing other templating languages, such as Hiccup for ClojureScript.

Scaffolding

Setting up a modern frontend project can be time-consuming. You need to install various tools and write several configuration files for linting, compiling, bundling, and setting up a development server. Tools like Vite relieve you of this burden.

To create a new project with Vite, execute the following command:

npm create vite@latest

This will generate the following files (depending on your choices):

├── README.md
├── eslint.config.js
├── index.html
├── package.json
├── public
│   └── vite.svg
├── src
│   ├── App.css
│   ├── App.tsx
│   ├── assets
│   │   └── react.svg
│   ├── index.css
│   ├── main.tsx
│   └── "vite-env.d.ts"
├── tsconfig.app.json
├── tsconfig.json
├── tsconfig.node.json
└── vite.config.ts

Vite is a modern frontend build tool renowned for its speed. It uses esbuild for transpilation and Rollup for bundling.

React Alternatives

Compared to other frameworks, React is lightweight. Unlike Vue or Svelte, React is not a programming language, and unlike Angular, it is not a full-fledged framework. Additionally, React is recognized for its stability.