Tutorial 2.1.1

React Fundamentals: Components, JSX, Props & State

Chapter 4 · Frontend Development
~3 hours Intermediate React · JSX · Hooks · State

Overview

React is the most popular library for building user interfaces. This tutorial introduces the foundational concepts every React developer needs: the Virtual DOM, JSX syntax, functional components, passing data with props, managing dynamic data with the useState hook, handling side effects with useEffect, and responding to user events. You will build a strong foundation to create interactive, modern web applications.

Why this matters: React's component‑based architecture makes it easy to build and maintain complex UIs. Mastering these fundamentals is essential for any frontend developer.

1. What is React & The Virtual DOM

React is a declarative, component‑based JavaScript library for building user interfaces. It was developed by Meta (formerly Facebook) and is now the industry standard for frontend development.

Declarative paradigm

You describe what the UI should look like for a given state, and React handles the updates efficiently. You don't manipulate the DOM directly.

The Virtual DOM

React maintains a lightweight virtual representation of the real DOM. When the application state changes, React compares the new virtual DOM with the previous one (diffing), and only updates the real DOM where changes occurred (reconciliation). This makes updates fast and efficient.

// React renders a component function Welcome({ name }) { return <h1>Hello, {name}!</h1>; } // React updates only the changed parts in the real DOM.

2. JSX Syntax

JSX stands for JavaScript XML. It is a syntax extension that allows you to write HTML‑like markup inside JavaScript files. It makes React code more readable and expressive.

Key rules

  • Wrap multiple elements: Use a fragment (<>...</>) or a single parent element.
  • JavaScript expressions: Use curly braces {} to embed any JavaScript expression.
  • Attributes: Use className instead of class, and htmlFor instead of for.
  • Self‑closing tags: Tags without children can be self‑closed (<img />).
function Greeting() { const name = "Alice"; return ( <div className="card"> <h1>Hello, {name}!</h1> <p>Today is {new Date().toLocaleDateString()}</p> </div> ); }

3. Components & Props

Components are the building blocks of a React application. They can be functional (functions) or class‑based (classes). Modern React uses functional components with hooks almost exclusively.

Props (Properties)

Props are read‑only inputs passed from a parent component to a child component. They allow you to make components reusable.

// Parent component function App() { return <UserCard name="Alice" age={30} />; } // Child component receiving props function UserCard({ name, age }) { return ( <div> <h2>{name}</h2> <p>Age: {age}</p> </div> ); }
Remember: Props are immutable. Never modify props directly inside the child component.

4. State with useState

While props are read‑only, state is data that changes over time and is managed inside a component. The useState hook allows functional components to have local state.

function Counter() { const [count, setCount] = useState(0); // Initial value 0 return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
  • useState returns an array with two elements: the current state and a setter function.
  • Calling the setter function triggers a re‑render of the component.
  • State updates may be asynchronous – use the functional update form if the new state depends on the previous state: setCount(prev => prev + 1).

5. Side Effects with useEffect

useEffect allows you to perform side effects in functional components. Common side effects: fetching data, subscribing to events, or manually changing the DOM.

function UserProfile({ userId }) { const [user, setUser] = useState(null); useEffect(() => { // Runs after the component mounts, and whenever userId changes fetch(`/api/users/${userId}`) .then(res => res.json()) .then(data => setUser(data)); }, [userId]); // Dependency array if (!user) return <div>Loading...</div>; return <div>{user.name}</div>; }

Dependency array controls when the effect runs: empty array = runs once on mount; with dependencies = runs when any dependency changes.

6. Event Handling

Event handlers in React follow the camelCase naming convention (onClick, onSubmit, onChange). They receive a synthetic event object that works consistently across browsers.

function Form() { const [inputValue, setInputValue] = useState(''); const handleChange = (event) => { setInputValue(event.target.value); }; const handleSubmit = (event) => { event.preventDefault(); alert('Submitted: ' + inputValue); }; return ( <form onSubmit={handleSubmit}> <input type="text" value={inputValue} onChange={handleChange} /> <button type="submit">Submit</button> </form> ); }

Quiz

Question 1

What is the primary purpose of the React Virtual DOM?

  • To store the application's entire state
  • To efficiently update the real DOM by minimising direct manipulations
  • To compile JSX into JavaScript
  • To manage routing between pages
Show answer
B. To efficiently update the real DOM by minimising direct manipulations.

Question 2

In JSX, how do you embed a JavaScript expression?

  • Using double quotes: "expression"
  • Using backticks: `expression`
  • Using curly braces: {expression}
  • Using square brackets: [expression]
Show answer
C. Using curly braces: {expression}.

Question 3

What happens when you call the state setter function (e.g., setCount) in a React component?

  • The component is destroyed
  • The component re‑renders with the new state
  • The state remains unchanged
  • The browser refreshes the page
Show answer
B. The component re‑renders with the new state.

Exercises

Exercise 1

Create a functional React component called Welcome that accepts a name prop and a greeting prop (default value: "Hello"). Render a heading: {greeting}, {name}!.

Sample answer
function Welcome({ name, greeting = "Hello" }) {
  return <h1>{greeting}, {name}!</h1>;
}

Exercise 2

Write a Toggle component that displays "ON" or "OFF" using state. Clicking a button toggles the state.

Sample answer
function Toggle() {
  const [isOn, setIsOn] = useState(false);
  return (
    <div>
      <p>Status: {isOn ? 'ON' : 'OFF'}</p>
      <button onClick={() => setIsOn(!isOn)}>Toggle</button>
    </div>
  );
}

Homework

Homework 1

Build a TodoList component that stores an array of todos in state. Each todo should have an id and text. Render the list and provide an input field and button to add new todos. (You don't need to implement deletion yet).

Sample answer
function TodoList() {
  const [todos, setTodos] = useState([]);
  const [input, setInput] = useState('');

  const addTodo = () => {
    if (input.trim() === '') return;
    setTodos([...todos, { id: Date.now(), text: input }]);
    setInput('');
  };

  return (
    <div>
      <ul>{todos.map(t => <li key={t.id}>{t.text}</li>)}</ul>
      <input value={input} onChange={e => setInput(e.target.value)} />
      <button onClick={addTodo}>Add</button>
    </div>
  );
}

Mini‑Project

Interactive Greeting Card Builder

Build a small React application with two components:

  • GreetingForm – contains an input field for the user's name and a dropdown (select) to choose a greeting type (e.g., "Hello", "Welcome", "Hola").
  • GreetingDisplay – displays the greeting in a styled box (e.g., with a background color or border). It should update immediately as the user types or selects.

All state should be managed in the parent component (App) and passed down via props.

Sample solution

App component (parent):

function App() {
  const [name, setName] = useState('');
  const [greetingType, setGreetingType] = useState('Hello');

  return (
    <div>
      <GreetingForm
        name={name} setName={setName}
        greetingType={greetingType} setGreetingType={setGreetingType} />
      <GreetingDisplay name={name} greetingType={greetingType} />
    </div>
  );
}

GreetingDisplay:

function GreetingDisplay({ name, greetingType }) {
  return (
    <div style={{ border: '2px solid #0284c7', padding: '1rem', borderRadius: '8px', marginTop: '1rem' }}>
      <h2>{greetingType}, {name || 'Guest'}!</h2>
    </div>
  );
}

Tutorial Summary

You learned the essential foundations of React: the Virtual DOM's role in performance, the JSX syntax, building functional components, passing data with props, managing dynamic data with the useState hook, handling side effects with useEffect, and responding to user events. You practiced these concepts through exercises and a mini‑project.

Key takeaway: React's component model encourages reusability and declarative thinking. Mastering these fundamentals is the first step towards building complex, high‑quality user interfaces.