πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
NEWSLIVESearch All Content
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

React Introduction: Components, JSX, Props, and State

React🟒 Free Lesson

React Introduction

React is a library for building user interfaces from isolated, reusable pieces called components. Instead of describing how to update the page step by step, you describe what the UI should look like for a given state, and React figures out the minimal DOM updates to get there. That inversion β€” declarative UI over imperative DOM manipulation β€” is why React scaled from Facebook's toolbar to most of the modern front-end ecosystem.

This lesson builds from zero: what a component is, how JSX differs from HTML, how data flows downward through props, how useState gives components memory, and the one rule about keys that saves hours of debugging.

Components as Functions of Props

A React component is a pure-ish function: props go in, a tree of elements comes out. Function components are just JavaScript functions returning JSX. Because they are ordinary functions, you can compose them freely β€” a page is a component made of components made of components.

function Greeting({ name, role = "guest" }) {
  return (
    <header className="greeting">
      <h1>Welcome, {name}</h1>
      <p>You are signed in as {role}.</p>
    </header>
  );
}

function HomePage() {
  return (
    <main>
      <Greeting name="Asha" role="editor" />
      <Greeting name="Visitor" />
    </main>
  );
}

Props flow one way: parent to child. A child can never write into its parent's props. When something needs to change, the change happens at the owner that holds the state, and new props trickle down β€” a pattern that makes data flow traceable in any React codebase.

JSX: Syntax Sugar With Rules

JSX looks like HTML embedded in JavaScript, but it compiles to nested React.createElement calls (or the newer automatic runtime). The differences that matter in daily work:

HTMLJSXWhy
class="x"className="x"class is a reserved word in JavaScript
for="q"htmlFor="q"Same reason
style="..."style={{ color: "red" }}Styles are objects, camelCased
<br><br /> or <br></br>Must be self-closed or paired
data-id="1"data-id="1"Custom data attributes pass through
Boolean attrsdisabled or disabled={true}JSX values are JavaScript expressions

Anything inside curly braces is evaluated: {user.name}, {items.length}, {condition && <p>Shown</p>}. Because JSX is an expression, you can store it in variables, pass it as arguments, and return it from functions β€” components themselves are just functions that return JSX.

Props: Documenting the Contract

Props are how a component declares what it needs. Destructure them in the signature and supply defaults right there, which doubles as documentation:

function PriceTag({ amount, currency = "EUR", discounted = false }) {
  const formatted = new Intl.NumberFormat("en-GB", {
    style: "currency",
    currency,
  }).format(amount);

  return (
    <span className={discounted ? "price price--sale" : "price"}>
      {discounted && <s className="price-was">{formatted}</s>}
      {formatted}
    </span>
  );
}

Children deserve special mention: whatever nests between a component's tags arrives as the children prop. Layout components (Card, Modal, PageSection) are built almost entirely on children, keeping them agnostic about content.

State With useState

Props are read-only; state is a component's private, mutable memory. useState returns the current value and a setter. Calling the setter schedules a re-render with the new value.

import { useState } from "react";

function Counter({ label, initial = 0 }) {
  const [count, setCount] = useState(initial);

  return (
    <div className="counter">
      <span>{label}: {count}</span>
      <button type="button" onClick={() => setCount(count + 1)}>
        Increment
      </button>
      <button type="button" onClick={() => setCount(initial)}>
        Reset
      </button>
    </div>
  );
}

Two rules keep state predictable. First, state is frozen in time for the duration of a render β€” a render closure always sees the values from its render, which is why rapid clicks should use the functional updater: setCount((c) => c + 1). Second, never mutate state in place; build a new object or array (setUser({ ...user, name: "Ben" })) so React can detect the change by reference.

Handling Events

React uses synthetic events with a camelCase naming convention: onClick, onChange, onSubmit. Handlers receive a pooled event object whose preventDefault() and stopPropagation() work as you expect. Inline arrow functions (onClick={() => setId(item.id)}) are idiomatic; hoisting handlers matters mainly for performance-critical lists and for effect dependencies later on.

Forms follow the same model. A controlled input ties its value to state, so the input never drifts from your data:

function NewsletterForm() {
  const [email, setEmail] = useState("");
  const [status, setStatus] = useState("idle");

  function handleSubmit(event) {
    event.preventDefault();
    setStatus("sending");
    // pretend API call
    Promise.resolve().then(() => {
      setStatus("sent");
    });
  }

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="email">Email</label>
      <input
        id="email"
        type="email"
        value={email}
        onChange={(event) => setEmail(event.target.value)}
        required
      />
      <button type="submit" disabled={status !== "idle"}>
        {status === "idle" ? "Subscribe" : "Working…"}
      </button>
      {status === "sent" && <p role="status">Thanks β€” check your inbox.</p>}
    </form>
  );
}

Rendering Lists and the Rules of Keys

Arrays of components render as lists. Every item needs a stable, unique key β€” a string or number identifying it across renders. React matches keys between renders to decide what to reuse, reorder, or destroy.

function TodoList({ items, onToggle }) {
  return (
    <ul>
      {items.map((item) => (
        <li key={item.id}>
          <label>
            <input
              type="checkbox"
              checked={item.done}
              onChange={() => onToggle(item.id)}
            />
            {item.text}
          </label>
        </li>
      ))}
    </ul>
  );
}

Array indexes work as keys only for static lists that never reorder. In any interactive list, index keys cause focus loss, wrong animations, and state attached to the wrong row after a deletion. Use a real id; generate one when creating the item, not when rendering.

When React Re-Renders

A component re-renders when its state changes, when a parent re-renders, or when a context value it consumes changes. It does not re-render because a prop object is "different but equal," and it does not re-render because a child's state changed β€” child state is private. Understanding this loop explains most performance advice: keep state as close to where it is used as possible, lift it only when siblings genuinely need to share it, and avoid premature memoization until you have measured a problem.

Conditional Rendering Patterns

Real interfaces hide, swap, and gate content constantly β€” loading spinners, empty states, permission-gated controls. React offers several idioms for each, and picking the right one keeps components readable.

The short-circuit pattern handles the simple case: render something only when a condition is truthy. Beware the numeric pitfall β€” a count of zero is falsy yet still a valid React child, so a careless short-circuit renders the literal zero on screen. Wrap the condition in an explicit boolean conversion or use a ternary.

Ternaries cover two-way swaps: loading versus loaded, signed-in versus signed-out. For three or more states, a lookup object at the top of the component beats a nesting tower of ternaries:

const ORDER_STATES = {
  loading: () => <p role="status">Loading orders…</p>,
  empty: () => <p>No orders yet.</p>,
  error: ({ message }) => <p role="alert">{message}</p>,
  ready: ({ orders }) => <OrderTable orders={orders} />,
};

function Orders({ status, orders, message }) {
  const render = ORDER_STATES[status] || ORDER_STATES.error;
  return (
    <section aria-labelledby="orders-heading">
      <h2 id="orders-heading">Orders</h2>
      {render({ orders, message })}
    </section>
  );
}

Early returns handle the guard-clause style: a component that needs a session checks it first and renders a sign-in prompt before any heavy markup is built. Whatever pattern you choose, keep the structure of the returned tree stable across states when possible β€” swapping a large subtree out and back on every fetch remounts children and discards their state, which is why many design systems prefer showing the previous data with a subtle busy indicator over blanking the interface entirely.

πŸ“Think in state, not in updates

When a bug appears, resist patching the DOM symptom. Ask what state, if rendered correctly, would produce the right screen β€” then make that state true. Most React bugs are stale or duplicated state: a derived value stored alongside its sources, a copy of a list that drifted from the original, a boolean that should have been a status enum. Rendering from a single, minimal state object turns layout bugs into data bugs, and data bugs are far easier to trace with logging and time-travel tools.

Common Mistakes

Using the array index as a key in a reorderable list

Fix: Use a stable unique id from your data; generate ids when items are created.

Mutating state objects directly and expecting a re-render

Fix: Create new objects or arrays with spread syntax and pass them to the setter.

Reading stale state inside rapid successive updates

Fix: Use the functional form: setCount((c) => c + 1).

Copying HTML attributes verbatim into JSX

Fix: Remember className, htmlFor, camelCase events, and self-closing tags.

Interview Questions

Q1: What does it mean that React components are pure functions?

Given the same props and state, a component returns the same element tree, and side effects are isolated (typically in effects). This purity is what lets React re-render cheaply and skip DOM work.

Q2: Why must list keys be stable?

React diffs children by key. Stable keys let React preserve component state and DOM nodes across reorders; index keys break that mapping when items are inserted or removed.

Q3: When does a child component re-render?

When its own state changes, when the parent re-renders and passes new props, or when a context value it subscribes to changes. Parent state never automatically equals child memoization.

Q4: Controlled vs uncontrolled inputs?

Controlled inputs derive their value from React state and update through onChange handlers; uncontrolled inputs keep their own DOM state and are read on submit via refs.

Key Takeaways

  • Components are functions of props that return JSX; compose them into trees.
  • JSX compiles to function calls β€” className, htmlFor, camelCase attributes, and self-closing tags are the daily differences.
  • Props flow one way, parent to child; state is a component's private mutable memory.
  • Never mutate state in place, and use functional updaters for updates that depend on the previous value.
  • List keys must be stable unique ids, not array indexes, whenever items can reorder or be removed.
  • A re-render is triggered by local state, a parent re-render, or a consumed context value β€” nothing else.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

β€”
β˜†β˜†β˜†β˜†β˜†
0 ratings

Rate & Feedback

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement