Learn Guide

React Fundamentals

Components, hooks, and the React mental model explained.

What is React?

React is a JavaScript library by Meta for building user interfaces. It uses a component-based model — the UI is composed of small, reusable components each managing their own state. React uses a virtual DOM for efficient updates.

Components & JSX

A component is a function that returns JSX — HTML-like syntax in JavaScript.

function Welcome({ name }) {
    return <h1>Hello, {name}!</h1>;
}

<Welcome name="Alice" />

JSX compiles to React.createElement(). Use className instead of class, and camelCase for events (onClick, onChange).

Props

Props are read-only inputs passed from parent to child:

function Card({ title, children }) {
    return (
        <div className="card">
            <h2>{title}</h2>
            {children}
        </div>
    );
}

State — useState

import { useState } from "react";

function Counter() {
    const [count, setCount] = useState(0);
    return (
        <button onClick={() => setCount(count + 1)}>
            Count: {count}
        </button>
    );
}

Never mutate state directly — always call the setter function.

Side Effects — useEffect

useEffect(() => {
    fetch("/api/data/" + id)
        .then(r => r.json())
        .then(setData);
}, [id]);  // re-runs when id changes
  • [] — runs once after first render
  • [dep] — runs when dep changes
  • No array — runs after every render

Common Hooks

Hook Purpose
useState Local component state
useEffect Side effects (fetch, subscriptions)
useContext Read a React context
useRef Reference DOM element or persist value
useMemo Cache expensive computation
useCallback Memoize a callback reference

Lists & Keys

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

Always provide a stable, unique key when rendering lists.