Introduction to React and Core Concepts

SA
StudyAI Editorial
Reviewed by StudyAI tutors
· Published Updated

From the https://www.youtube.com/watch?v=5yw1YH7YA7c&t=2725s curriculum

Introduction to React and Core Concepts

TL;DR

React is a JavaScript library for building user interfaces by breaking them down into reusable, self-contained components. It uses a concept called the "virtual DOM" to efficiently update what you see on the screen. Understanding components, props, state, and the rendering process is key to building React applications.

1. The Mental Model

Think of your website as a collection of LEGO bricks. Each brick is a "component" that you can assemble, reuse, and customize. React helps you manage these bricks, ensuring they fit together perfectly and only changing the ones that need to when something updates.

2. The Core Material

React helps you build interactive user interfaces using a component-based approach. This means you break your UI into smaller, independent, and reusable pieces.

What is a Component?

Detailed view of electronic components on a circuit board showcasing capacitors and semiconductors.
Photo by Muffin Creatives on Pexels

A component is like a blueprint for a part of your UI. It's a JavaScript function (or class, but functional components are more common now) that returns JSX, which looks like HTML but allows you to embed JavaScript.

Here's a simple functional component:

// src/App.js
function WelcomeMessage() {
  return <h1>Hello, React!</h1>;
}

export default WelcomeMessage; // Makes it available to other files

You'd then render this component in your main index.js file:

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import WelcomeMessage from './App'; // Import your component

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <WelcomeMessage /> {/* This is how you use your component */}
  </React.StrictMode>
);

Props: Passing Data Down

Close-up of a modern digital sound interface screen displaying tuning, saturation, and filter settings.
Photo by Egor Komarov on Pexels

Props (short for properties) are how you pass data from a parent component to a child component. They're like arguments to a function. Props are read-only; a child component should never directly modify the props it receives.

function Greeting(props) {
  return <h2>Hello, {props.name}!</h2>;
}

function App() {
  return (
    <div>
      <Greeting name="Alice" /> {/* Passing 'Alice' as a prop */}
      <Greeting name="Bob" />   {/* Passing 'Bob' as a prop */}
    </div>
  );
}

export default App;

State: Managing Data within a Component

Detailed view of an open hard drive showing its internal mechanisms and disk platters.
Photo by William Warby on Pexels

State is data that a component manages internally and can change over time. When a component's state changes, React re-renders that component and its children to reflect the new state. You use the useState hook for this in functional components.

import React, { useState } from 'react';

function Counter() {
  // 'count' is the state variable, 'setCount' is the function to update it
  const [count, setCount] = useState(0); // Initial state is 0

  const increment = () => {
    setCount(count + 1); // Update the state
  };

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={increment}>Click me</button>
    </div>
  );
}

export default Counter;

The Virtual DOM and Reconciliation

A priest in a traditional vestment sits in a confessional box, reflecting quietly.
Photo by cottonbro studio on Pexels

React uses a virtual DOM, which is a lightweight copy of the actual browser DOM. When state or props change, React:
1. Creates a new virtual DOM tree.
2. Compares this new tree with the previous virtual DOM tree (this process is called reconciliation).
3. Identifies only the minimum necessary changes.
4. Updates only those specific changes in the real browser DOM.

This efficient update mechanism is why React applications feel fast.

graph TD
    A["Initial Render (State/Props)"] --> B["Create Virtual DOM (V1)"];
    B --> C["Render Real DOM"];
    D["State/Props Change"] --> E["Create New Virtual DOM (V2)"];
    E --> F["Diffing (V1 vs V2)"];
    F --> G["Identify Minimal Changes"];
    G --> H["Update Real DOM (Only changes)"];
    H --> I["UI Updates"];

3. Worked Example

Let's combine components, props, and state to build a simple task list.

// src/components/TaskItem.js
import React from 'react';

function TaskItem({ task, onDelete }) {
  return (
    <li>
      {task.text}
      <button onClick={() => onDelete(task.id)} style={{ marginLeft: '10px' }}>
        Delete
      </button>
    </li>
  );
}

export default TaskItem;

// src/App.js
import React, { useState } from 'react';
import TaskItem from './components/TaskItem'; // Assuming TaskItem.js is in a 'components' folder

function App() {
  const [tasks, setTasks] = useState([
    { id: 1, text: 'Learn React' },
    { id: 2, text: 'Build a project' },
    { id: 3, text: 'Deploy to Netlify' },
  ]);
  const [newTaskText, setNewTaskText] = useState('');

  const addTask = () => {
    if (newTaskText.trim() === '') return; // Don't add empty tasks
    const newId = tasks.length > 0 ? Math.max(...tasks.map(task => task.id)) + 1 : 1;
    setTasks([...tasks, { id: newId, text: newTaskText }]);
    setNewTaskText(''); // Clear input field
  };

  const deleteTask = (idToDelete) => {
    setTasks(tasks.filter(task => task.id !== idToDelete));
  };

  return (
    <div>
      <h1>My To-Do List</h1>
      <input
        type="text"
        value={newTaskText}
        onChange={(e) => setNewTaskText(e.target.value)}
        placeholder="Add a new task"
      />
      <button onClick={addTask}>Add Task</button>

      <ul>
        {tasks.map(task => (
          // Pass 'task' object as prop, and a function 'deleteTask' as prop
          <TaskItem key={task.id} task={task} onDelete={deleteTask} />
        ))}
      </ul>
    </div>
  );
}

export default App;

In this example:
- App is the parent component holding the main state (tasks, newTaskText).
- TaskItem is a child component that receives task details and a onDelete function as props.
- When you type in the input, newTaskText state updates.
- When you click "Add Task", addTask updates the tasks state.
- When you click "Delete" on a TaskItem, it calls the onDelete prop, which triggers deleteTask in the parent App to update the tasks state, causing a re-render.

4. Key Takeaways

  • React is a JavaScript library for building user interfaces with a component-based architecture.
  • Components are reusable, self-contained blocks of UI code, typically JavaScript functions that return JSX.
  • Props are used to pass data from parent components to child components and are read-only.
  • State is internal data managed by a component that can change over time, triggering re-renders.
  • The useState hook is how you manage state in functional components.
  • React uses a virtual DOM and reconciliation to efficiently update the actual browser DOM, leading to better performance.
  • When state or props change, React intelligently updates only the necessary parts of the UI.

Common Mistakes to Avoid

  • Modifying props directly: Never try to change props.someValue inside a child component; props are read-only.
  • Modifying state directly: Don't do count = count + 1 or tasks.push(newTask). Always use the state setter function (setCount, setTasks) to update state.
  • Forgetting key prop in lists: When rendering a list of components (like TaskItem above), always provide a unique key prop for each item. This helps React efficiently update the list.
  • Using index as a key if list items can be reordered or removed: While index works for static lists, it can cause bugs if the order changes. Prefer a unique ID from your data.

5. Now Try It

Modify the Counter component from the "State" section. Add another button that decrements the count. Also, add a button that resets the count back to zero.

What success looks like: You'll have three buttons: "Click me" (increments), "Decrement" (decrements), and "Reset" (sets count to 0), all correctly updating the displayed count.

Frequently asked about Introduction to React and Core Concepts

React is a JavaScript library for building user interfaces by breaking them down into reusable, self-contained components. It uses a concept called the "virtual DOM" to efficiently update what you see on the screen. Read the full notes above for the details.

Introduction to React and Core Concepts is a core topic in https://www.youtube.com/watch?v=5yw1YH7YA7c&t=2725s. Most exam papers test it via a mix of definitions, worked examples, and applied problems. The notes above cover the high-yield sub-topics, common pitfalls, and the kind of questions examiners typically set.

Yes. Every note in the StudyAI Campus Hub is free to read. Create a free account if you want to clone the full plan, generate your own notes from your textbook, or get AI-powered practice quizzes and flashcards.

Get the full https://www.youtube.com/watch?v=5yw1YH7YA7c&t=2725s curriculum

Clone the complete plan to your dashboard for unlimited AI-generated notes, practice quizzes, and a personalised revision schedule.

Create Free Account