Intro

  • React is a javascript library for building dynamic and interactive user interfaces
  • Typescript is a superset of js that adds static typing to the language and helps catch errors earlier in the development process

Resources

React with CodePen

You need to add react as a JS dependency. Click on “Settings” at the top of your pen, then “Javascript” in the pop-up. Under “javascript preprocessor”, select Babel, and under “add external scripts/pens”, type “react”. Select both react and react-dom. You should now be ready to use React.

React Libraries

React Hooks

https://react.dev/reference/react/hooks

useState

https://react.dev/reference/react/useState

useState

useState is a React Hook that lets you add a state variable to your component.

const [state, setState] = useState(initialState)
import { useState } from 'react';
 
const [name, setName] = useState('Edward');
 
function handleClick() {
  setName('Taylor');
  setAge(a => a + 1);
  // ...

useEffect

useEffect is a React Hook that lets you synchronize a component with an external system.

useEffect(setup, dependencies?)

import { useState, useEffect } from 'react';
import { createConnection } from './chat.js';
 
function ChatRoom({ roomId }) {
  const [serverUrl, setServerUrl] = useState('https://localhost:1234');
 
  useEffect(() => {
    const connection = createConnection(serverUrl, roomId);
    connection.connect();
    return () => {
      connection.disconnect();
    };
  }, [serverUrl, roomId]);
  // ...
}

Create a button

How to create a React Button

Hydration

Hydration is when React converts the pre-rendered HTML from the server into a fully interactive application by attaching event handlers.

Dan Abramov writes it as: “It’s like watering the “dry” HTML with the “water” of interactivity and event handlers.”

The server sends the client HTML along with a link to the JS to download. The JS gets downloaded and then “hydrates” the page taking it from a plain page to one with interactivity meaning adding handlers to buttons, events to elements on the page like onClick and so forth.

  • Example: When you visit a Next.js site, the server sends static HTML to the browser
<!-- Server-side rendered (SSR) HTML -->
<div id="root">
  <button>Count: 0</button>
</div>
  • After the page loads, React runs on the client, taking the static HTML and “hydrating” it (attaches event handlers, connects state, etc.)
// React client bundle
ReactDOM.hydrate(<App />, document.getElementById('root'));
  • Now the button works
<button onClick={increment}>Count: 0</button>