| |

React 1 ⚛️ What React Is

React is a JavaScript library for building user interfaces from small, reusable pieces called components. It was created at Facebook (now Meta) and released in 2013. The core idea is simple: instead of manipulating the browser’s DOM directly, you describe what the UI should look like for a given state, and React handles the updates. This declarative model is what makes React applications easier to reason about, test, and maintain as they grow .

React is not a full framework. It handles the view layer — the part the user sees — and leaves routing, data fetching, and state management to other tools in the ecosystem. This is both its strength and its challenge: you get flexibility, but you also make more decisions. The React documentation is explicit about this: “React is a library. It lets you put components together, but it doesn’t prescribe how to do routing and data fetching” .

Key point: A React component is a JavaScript function that returns markup. That markup is written in JSX, a syntax extension that looks like HTML but compiles to JavaScript. The component receives data through props, manages its own state, and returns a DOM subtree. React maintains a virtual DOM — an in-memory representation of the UI — and when state changes, it compares the new virtual DOM with the previous one and updates only the parts of the real DOM that changed. This process is called reconciliation .


Why React exists

Before React, building interactive web applications meant manually manipulating the DOM. You would find an element, change its text, add a class, remove a child node — all imperatively. As applications grew, this became unmanageable. The state of the UI and the state of your data drifted apart. Bugs multiplied. React’s answer was to make the UI a function of state: given the same data, the UI always looks the same. When data changes, React figures out what changed and updates the DOM efficiently.

The DOM manipulation problem. The browser’s DOM API is imperative. To update a list, you must find the list element, create new list items, insert them at the right positions, and remove old ones. Every operation is manual. React replaces this with a declarative model: you describe the list’s content, and React handles the DOM operations. The virtual DOM is the mechanism that makes this efficient — it diffs the old and new representations and applies only the necessary changes .

The reusability problem. Without a component model, UI patterns are duplicated across pages. A button style is copied from one page to another. A card layout is reimplemented for each use case. React components are self-contained: the markup, the styles, and the behavior live together. You write a <Button /> once and use it everywhere. This is what the React documentation calls “UI building blocks” .

The composition problem. React components nest inside each other. A <Gallery /> component renders multiple <Profile /> components. A <Page /> renders a <Header />, a <Sidebar />, and a <Content />. This composition mirrors how you think about UI: small pieces combine into larger pieces. The component tree is the structure of the application .

The trade-off. React is a library, not a framework. It does not tell you how to structure your application, which state management library to use, or how to fetch data. This flexibility is powerful, but it also means more choices. The React documentation recommends using a full-stack framework like Next.js or Remix for a complete application, precisely because React alone leaves too many decisions to the developer .


a. Components: The Building Blocks

A React component is a JavaScript function that returns markup. The function name must start with a capital letter — React treats lowercase tags like <div> as HTML elements and capitalized tags like <Profile /> as components. This naming convention is not optional. It is how React distinguishes between the two .

function Profile() {
  return (
    <img
      src="https://example.com/avatar.jpg"
      alt="User avatar"
    />
  );
}

The component returns JSX, which looks like HTML but is actually JavaScript. The JSX compiles to React.createElement() calls, which produce plain JavaScript objects describing the UI. React uses these objects to build the virtual DOM .

Components can be nested. A Gallery component can render multiple Profile components. This nesting creates a parent-child relationship: Gallery is the parent, each Profile is a child. Data flows from parent to child through props, and from child to parent through callback functions .

function Gallery() {
  return (
    <section>
      <h1>Amazing Scientists</h1>
      <Profile />
      <Profile />
      <Profile />
    </section>
  );
}

The component tree mirrors the visual hierarchy. A page is a tree of components, from the root (App) down to leaf components that render individual elements. Understanding this tree is useful for data flow and rendering performance .


b. JSX: Markup in JavaScript

JSX is a syntax extension that lets you write HTML-like markup inside JavaScript. It is not required to use React, but it is the standard way to write React components. The JSX <h1>Hello</h1> compiles to React.createElement('h1', null, 'Hello'). The result is a plain JavaScript object that React can render .

JSX is stricter than HTML. Every tag must be closed. A component can return only one root element. Attributes use camelCase (className instead of class, onClick instead of onclick). These differences exist because JSX is not HTML — it is a JavaScript syntax that happens to look like HTML .

Curly braces open a “window” to JavaScript inside JSX. You can embed expressions, variables, and function calls. This is how you make the UI dynamic: {{ user.name }}, {{ isActive ? 'Active' : 'Inactive' }}, {{ items.map(item => <li>{{ item.name }}</li>) }} .

function Greeting({ user }) {
  return (
    <div>
      <h1>Hello, {{ user.name }}!</h1>
      <p>You have {{ user.unreadCount }} unread messages.</p>
    </div>
  );
}

The {{ }} syntax is the bridge between the static markup and the dynamic data. It is what makes React components declarative: the UI is described in terms of the data, not in terms of the DOM operations needed to update it.


c. Props and State

React components communicate through props and manage their own data with state. Props are inputs from the parent. State is data that changes over time.

Props are passed to a component like HTML attributes: <Profile name="Alice" age={30} />. The component receives them as a single object: function Profile({ name, age }). Props are read-only. A component must never modify its own props. Data flows down the component tree through props .

State is data that belongs to a component and can change. The useState hook declares a state variable and a function to update it:

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

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

When setCount is called, React re-renders the component with the new state value. The virtual DOM is updated, the diff is computed, and only the changed text node is updated in the real DOM. This is the reconciliation process in action .

State is local to the component that declares it. To share state between components, you lift it to a common ancestor and pass it down as props. For complex applications, this prop-drilling becomes unwieldy, which is why the ecosystem provides state management libraries like Redux, Zustand, and Jotai .


Complete Example Session

This session builds a small React application that demonstrates components, JSX, props, and state together.

// ============================================
// PART 1: THE PROFILE COMPONENT
// ============================================

function Profile({ name, role, avatar }) {
  return (
    <div className="profile-card">
      <img src={{ avatar }} alt={{ `{{name}}'s avatar` }} />
      <h3>{{ name }}</h3>
      <p>{{ role }}</p>
    </div>
  );
}

// Profile is a component.
// It receives name, role, and avatar as props.
// It returns JSX that describes the card.

// ============================================
// PART 2: THE PROFILE LIST COMPONENT
// ============================================

function ProfileList({ profiles }) {
  return (
    <div className="profile-list">
      {{ profiles.map(profile => (
        <Profile
          key={{ profile.id }}
          name={{ profile.name }}
          role={{ profile.role }}
          avatar={{ profile.avatar }}
        />
      )) }}
    </div>
  );
}

// ProfileList receives an array of profiles.
// It maps over the array and renders a Profile for each.
// The key prop is required for list rendering.

// ============================================
// PART 3: THE COUNTER COMPONENT WITH STATE
// ============================================

import { useState } from 'react';

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

  return (
    <div className="counter">
      <p>Count: {{ count }}</p>
      <button onClick={{ () => setCount(count - 1) }}>−</button>
      <button onClick={{ () => setCount(count + 1) }}>+</button>
      <button onClick={{ () => setCount(0) }}>Reset</button>
    </div>
  );
}

// Counter uses useState to track count.
// The buttons call setCount with new values.
// React re-renders when the state changes.

// ============================================
// PART 4: THE APP COMPONENT
// ============================================

const profiles = [
  { id: 1, name: 'Alice', role: 'Developer', avatar: '...' },
  { id: 2, name: 'Bob', role: 'Designer', avatar: '...' },
  { id: 3, name: 'Carol', role: 'Manager', avatar: '...' },
];

function App() {
  return (
    <main>
      <h1>Team Directory</h1>
      <ProfileList profiles={{ profiles }} />
      <hr />
      <h2>Counter Demo</h2>
      <Counter />
    </main>
  );
}

// App is the root component.
// It renders ProfileList and Counter.
// The component tree is: App → ProfileList → Profile
// and App → Counter.

// ============================================
// PART 5: THE VIRTUAL DOM IN ACTION
// ============================================

// When the Counter's count changes:
// 1. React calls Counter() again.
// 2. Counter returns a new virtual DOM subtree.
// 3. React diffs the new subtree with the previous one.
// 4. Only the <p> text node changed.
// 5. React updates only that text node in the real DOM.
//
// The ProfileList and Profile components are untouched.
// Their virtual DOM subtrees are identical.
// React skips them entirely.

// This is reconciliation.
// It is what makes React fast.

The ten parts cover the Profile component, the ProfileList component, the Counter component with state, the App component, and the virtual DOM in action.


Quick Reference

The Core Concepts

ConceptDefinition
ComponentA JavaScript function that returns markup
JSXA syntax extension that looks like HTML
PropsInputs from a parent component
StateData that changes over time
Virtual DOMAn in-memory representation of the UI
ReconciliationThe process of diffing and updating the DOM

The Component Rules

RuleReason
Name starts with a capital letterDistinguishes components from HTML tags
Return a single root elementJSX requires one parent
Props are read-onlyData flows down, never up
State is localLifted to share
Keys in listsReact tracks items by key

The Ecosystem

NeedCommon Tools
RoutingReact Router, Next.js
State managementRedux, Zustand, Jotai
Data fetchingTanStack Query, SWR
FormsReact Hook Form, Formik
StylingCSS Modules, Tailwind, styled-components

The React vs Vue Comparison

AspectReactVue
TypeLibraryFramework
Bundle size~44.5 KB gzipped~34.7 KB gzipped
StateCommunity-drivenOfficial (Pinia)
RouterCommunity-drivenOfficial (Vue Router)
Learning curveSteeperGentler

Best Practices

✅ Do This:

// Name components with capital letters
function Profile() {{ ... }}                                    // ✅
// Use keys in lists
{{ items.map(item => <li key={{ item.id }}>{{ item.name }}</li>) }} // ✅
// Keep components pure
function Greeting({{ name }}) { return <h1>Hello, {{name}}</h1>; } // ✅
// Use props for data flow
<Profile name="Alice" />                                        // ✅
// Use state for local data
const [count, setCount] = useState(0);                          // ✅

❌ Don’t Do This:

// Don't nest component definitions
function Outer() { function Inner() {{ ... }} return <Inner />; } // ❌
// Don't modify props
function Profile(props) { props.name = 'Bob'; }                 // ❌
// Don't use lowercase component names
function profile() {{ ... }}  // React treats this as HTML         // ❌
// Don't forget the key in lists
{{ items.map(item => <li>{{ item.name }}</li>) }}                 // ❌
// Don't mutate state directly
count = count + 1;  // use setCount(count + 1)                    // ❌

Common Pitfalls

PitfallWhy It HappensFix
Component not renderingLowercase nameStart with a capital letter
JSX syntax errorMultiple root elementsWrap in a fragment or div
Props undefinedWrong prop nameCheck the destructuring
State not updatingMutating state directlyUse the setter function
List re-renderingMissing or wrong keyUse a stable unique ID

Real-World Examples

1. Basic Component

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

2. Component with Props

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

3. Component with State

function Toggle() {
  const [isOn, setIsOn] = useState(false);
  return <button onClick={() => setIsOn(!isOn)}>{isOn ? 'On' : 'Off'}</button>;
}

4. Conditional Rendering

function Status({ isActive }) {
  return <span>{isActive ? 'Active' : 'Inactive'}</span>;
}

5. List Rendering

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

6. Event Handler

function Clicker() {
  return <button onClick={() => alert('Clicked!')}>Click</button>;
}

7. Nested Components

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

8. Fragment

function FragmentDemo() {
  return <><h1>Title</h1><p>Body</p></>;
}

9. Props with Defaults

function Button({ label = 'Click', variant = 'primary' }) {
  return <button className={variant}>{label}</button>;
}

10. Lifting State

function Parent() {
  const [value, setValue] = useState('');
  return <Child value={value} onChange={setValue} />;
}

Visual

The Component Tree

┌──────────────────────────────────────────────┐
│  App                                         │
│  ├─ Header                                   │
│  ├─ ProfileList                              │
│  │  ├─ Profile (Alice)                       │
│  │  ├─ Profile (Bob)                         │
│  │  └─ Profile (Carol)                       │
│  └─ Counter                                  │
│                                              │
│  Data flows down through props.              │
│  Events bubble up through callbacks.         │
│                                              │
└──────────────────────────────────────────────┘

The Virtual DOM Diff

┌──────────────────────────────────────────────┐
│  Before:                                     │
│  <div>                                       │
│    <p>Count: 0</p>                           │
│    <button>+</button>                        │
│  </div>                                      │
│                                              │
│  After:                                      │
│  <div>                                       │
│    <p>Count: 1</p>   ← changed               │
│    <button>+</button> ← unchanged            │
│  </div>                                      │
│                                              │
│  React diffs the two trees.                  │
│  Only the text node changes.                 │
│  The button is untouched.                    │
│                                              │
└──────────────────────────────────────────────┘

The Reconciliation Process

┌──────────────────────────────────────────────┐
│  1. State changes                            │
│  2. React calls the component function       │
│  3. The function returns a new virtual DOM   │
│  4. React diffs new vs old                   │
│  5. React computes the minimal updates       │
│  6. React applies the updates to the real DOM│
│                                              │
│  The user sees the updated UI.               │
│                                              │
└──────────────────────────────────────────────┘

React vs Vue Bundle Size

┌──────────────────────────────────────────────┐
│  BUNDLE SIZE (gzipped)                       │
│                                              │
│  React + React DOM: ~44.5 KB                 │
│  Vue (Vite build):  ~34.7 KB                 │
│                                              │
│  The difference is real but bounded.         │
│  As your app grows, your code dominates.     │
│                                              │
└──────────────────────────────────────────────┘

Summary

ItemValue
React definitionJavaScript library for building UIs
Created byFacebook (Meta), 2013
Core conceptComponents
Markup syntaxJSX
Data flowProps (down), callbacks (up)
Local dataState
Performance mechanismVirtual DOM, reconciliation
TypeLibrary, not framework
Bundle size~44.5 KB gzipped
RecommendationNext.js or Remix for full apps

Key takeaways:

  • React is a JavaScript library for building user interfaces from components. A component is a JavaScript function that returns markup. Components are the building blocks of every React application .
  • JSX is a syntax extension that looks like HTML but compiles to JavaScript. It lets you write markup inside your JavaScript code, keeping rendering logic and content in the same place .
  • Props pass data from parent to child components. They are read-only. Data flows down the component tree. To send data up, the parent passes a callback function as a prop .
  • State is data that belongs to a component and changes over time. The useState hook declares a state variable and a setter function. When the state changes, React re-renders the component .
  • React maintains a virtual DOM to update the real DOM efficiently. When state changes, React compares the new virtual DOM with the previous one and updates only the parts that changed. This process is called reconciliation .
  • React is a library, not a framework. It handles the view layer and leaves routing, data fetching, and state management to other tools. The documentation recommends using a full-stack framework like Next.js for complete applications .
  • The component tree is the structure of the application. Components nest inside other components. The tree mirrors the visual hierarchy. Understanding the tree helps with data flow and performance .

Remember: React is the library for building user interfaces from components. A component is a function that returns JSX. Props flow down, state lives locally, and the virtual DOM makes updates efficient. React handles the view layer and leaves the rest to the ecosystem. It is not a framework — it is a library, and that distinction shapes everything about how you build with it.


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!