โš›๏ธ

React

๐Ÿง‘โ€๐Ÿณ Cook

Components that react

React is a library for building user interfaces with reusable components.


Key concepts

ConceptWhat it is
ComponentReusable UI piece
PropsData the component receives
StateInternal component data
HookFunction to add functionality

Your first component

// Functional component
function Greeting({ name }: { name: string }) {
  return <h1>Hello, {name}!</h1>
}

// Usage
<Greeting name="Ana" />

useState: Local state

import { useState } from 'react'

function Counter() {
  const [count, setCount] = useState(0)

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        +1
      </button>
    </div>
  )
}

useEffect: Side effects

import { useState, useEffect } from 'react'

function Data() {
  const [data, setData] = useState(null)

  useEffect(() => {
    fetch('/api/data')
      .then(res => res.json())
      .then(setData)
  }, []) // [] = only on mount

  return <div>{JSON.stringify(data)}</div>
}

Common pattern: List

interface Item {
  id: string
  name: string
}

function List({ items }: { items: Item[] }) {
  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  )
}

Forms

function Form() {
  const [text, setText] = useState('')

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    console.log('Submitted:', text)
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={text}
        onChange={e => setText(e.target.value)}
      />
      <button type="submit">Submit</button>
    </form>
  )
}

Practice

โ†’ Todo App with React


Useful links