React .js

The UI as
a Function

React is a JavaScript library for building user interfaces. Ideally, it lets you describe your UI as a function of your state: UI = f(state).

00 / Setup

Getting Started

React is a library, not a framework. You can add it to an existing HTML page, but for new projects, it's best to use a toolchain. You'll need Node.js installed.

The Classic Way

Create React App (CRA)

Good for beginners, but slower and less flexible than modern tools.

npx create-react-app my-app
cd my-app
npm start

The Modern Way

Vite (Recommended)

Extremely fast build tool. Use this for production apps.

npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev
01 / Building Blocks

Components & JSX

React apps are made out of components. A component is a piece of the UI (User Interface) that has its own logic and appearance. React components are JavaScript functions that return markup.

The Code

function Button() { return ( <button className="btn"> Click me </button> ); }

JSX allows writing HTML-like syntax inside JavaScript.

The Result

Why Components?

1. Reusability: Write a button once, use it everywhere. Consistency is automatic.

2. Isolation: If a button breaks, it doesn't crash the whole header. Each component manages its own errors.

The Lifecycle

  • Mounting: Born. Added to the screen (DOM).
  • Updating: Changed. Re-rendered due to new props or state.
  • Unmounting: Died. Removed from the screen.

Quick Check

True or False: React component names must always start with a capital letter?

01 / Data Flow

Props vs State

PROPS (Properties)

  • Passed into a component (like function arguments).
  • Immutable (Read-Only) by the receiving component.
  • Used to configure a component.

STATE

  • Managed within the component.
  • Mutable (Can change over time).
  • Triggers a re-render when changed.

Interactive State Demo

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

Quick Check

Which of these is mutable (can be changed by the component)?

02 / Logic

Hooks

Hooks let you use state and other React features without writing a class.

useState

Adds local state to function components.

const [val, setVal] = useState(0);

useEffect

Performs side effects (API calls, DOM updates).

useEffect(() => { ... }, [deps]);

useContext

Subscribes to React Context without nesting.

const value = useContext(MyContext);

useRef

Persists values between renders without causing re-renders.

const ref = useRef(initial);

⚠️ The 2 Rules of Hooks

1. Only Call at the Top Level

Don't call Hooks inside loops, conditions, or nested functions.

// ❌ Bad
if (data) { useEffect(...) }
2. Only Call from React Functions

Call Hooks from function components or custom Hooks.

// ✅ Good
function Component() { useState(...) }

Quick Check

Can you use Hooks inside standard Class components?

02 / Logic

Side Effects & Lifecycle

Components need to do more than just display data—they need to fetch data, set up subscriptions, or manually change the DOM (like focusing an input). These are called "Side Effects".

The useEffect Hook

useEffect tells React that your component needs to do something after render. You control when it runs using a "Dependency Array".

Run Once (Mount)
useEffect(() => {
  fetchData();
}, []);

Empty array []. Runs only once after the first render (like componentDidMount).

Run on Change
useEffect(() => {
  update(id);
}, [id]);

Runs after mount AND whenever id changes.

Run Every Render
useEffect(() => {
  log();
});

No array. Runs after every single render. (Be careful!).

The Cleanup Function

Sometimes effects create "mess" (open connections, timers). If you return a function from useEffect, React runs it to clean up before running the effect again (or unmounting).

useEffect(() => {
  const timer = setInterval(tick, 1000);
  return () => clearInterval(timer); // Cleanup!
}, []);

Quick Check

When does useEffect(fn, []) (with an empty array) run?

03 / Internals

The Virtual DOM

React creates a lightweight copy of the DOM called the Virtual DOM. When state changes, React compares the new Virtual DOM with the previous one (Diffing) and only updates the actual DOM where necessary (Reconciliation).

⚡ Performance Note: Batching React doesn't update the screen instantly for every state change. It "batches" (groups) multiple state updates into a single re-render to save performance. It's like a waiter taking all orders at a table before going to the kitchen, instead of running back and forth for every person.

Previous

New VDOM

Real DOM

03 / State Management

Context API

Passing props down multiple levels ("Prop Drilling") is tedious. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.

Global Theme State App Component
App Provider
Nav
Button
Layout
ThemeBtn
04 / Scaling

Performance

React is fast by default, but complex apps need optimization. Re-rendering large trees unnecessarily can cause lag.

React.memo

HOC that skips re-rendering a component if its props haven't changed.

useMemo

Caches the result of a calculation between re-renders.

useCallback

Caches a function definition to prevent it from changing on every render.

05 / The Landscape

Ecosystem

React Router

Standard library for routing in React. Enables Single Page Applications (SPAs) with client-side navigation.

Next.js / Remix

Full-stack frameworks built on React. They add Server-Side Rendering (SSR), Static Site Generation (SSG), and API routes.

React Native

A framework for building native apps for iOS and Android using React components.

Glossary

Key Definitions

Component

A reusable, self-contained piece of UI logic and structure.

JSX

JavaScript XML. A syntax extension that lets you write HTML-like code in JS.

State

Data managed within a component that triggers a re-render when changed.

Props

Read-only data passed from a parent component to a child.

Virtual DOM

A lightweight in-memory representation of the real DOM used for performance.

Reconciliation

The process of figuring out the most efficient way to update the UI.

Hook

A special function that lets you "hook into" React features like state and lifecycle.

Context

A way to pass data through the component tree without manually passing props at every level.

Memoization

An optimization technique used to speed up computer programs by caching the results of expensive function calls.

Prop Drilling

The process of passing data from a parent component down to a deep child component through intermediate components.

SPA

Single Page Application. A web app that interacts with the web browser by dynamically rewriting the current web page with new data.

SSR

Server-Side Rendering. Generating HTML on the server for each request, improving SEO and initial load performance.

04 / Assessment

Knowledge Check