All Cheatsheets

React.js

React.js

React is a JavaScript library for building user interfaces, created by Meta (Facebook) in 2013. Instead of manually updating the page when data changes, you describe what the UI should look like for a given state, and React efficiently updates the actual page to match. It is component-based: you build small, reusable pieces and compose them into complex interfaces.

Key Features -
  • Component-Based : UIs are built from independent, reusable components, each managing its own logic and appearance.
  • Declarative : You describe the desired result for the current state; React figures out the DOM changes. This is easier to reason about than manual, step-by-step DOM updates.
  • Virtual DOM : React keeps a lightweight copy of the DOM in memory, compares it after each change, and updates only what actually differs, which makes updates fast.
  • Unidirectional Data Flow : Data flows down from parent to child through props, making the app predictable and easier to debug.
  • JSX : A syntax that lets you write HTML-like markup directly inside JavaScript.
  • Learn Once, Write Anywhere : The same ideas power React for web, React Native for mobile, and more.

Library vs Framework : React is a library focused only on the view (the UI). Unlike a full framework such as Angular, it leaves routing, data fetching, and state management to separate packages that you choose, which is why React apps are assembled from an ecosystem of tools.

How React Works

React keeps the UI in sync with your data through a render cycle driven by state. You never touch the real DOM directly; you change state, and React updates the page for you.

The Render Cycle -
  • 1. Render : A component is a function that returns JSX describing the UI for the current props and state.
  • 2. Virtual DOM : React builds a virtual DOM tree from that JSX, an in-memory representation of the UI.
  • 3. State Change : When state or props change (for example, a button click updates a counter), React re-runs the component function to get a new virtual DOM.
  • 4. Diffing (Reconciliation) : React compares the new virtual DOM with the previous one to find exactly what changed.
  • 5. Commit : React updates only the changed parts of the real DOM, leaving the rest untouched, which is what makes it efficient.
State change -> Re-render component (run the function) -> New Virtual DOM -> Diff against old Virtual DOM -> Update only changed real DOM nodes -> Screen updates

Setup & Commands

Modern React projects are created with a build tool. Vite is the current default (fast and light); Create React App (CRA) is the older, now deprecated tool. React needs Node.js and a package manager installed.

# create a new project with Vite npm create vite@latest my-app # choose the "React" framework, then: cd my-app npm install # install dependencies npm run dev # start dev server with hot reload npm run build # bundle for production npm run preview # preview the production build # add a package npm install react-router-dom
  • react & react-dom : The two core packages. react defines components and hooks; react-dom renders them into the browser DOM.
  • Hot Reload (HMR) : The dev server updates the browser instantly as you edit, without a full page refresh.
  • Node Requirement : React tooling runs on Node.js, and packages install through npm.

Project Structure

A typical Vite React project separates the entry files from your components and assets.

my-app/ ├── node_modules/ # installed packages ├── public/ # static files served as-is ├── src/ │ ├── components/ # reusable UI components │ ├── pages/ # route-level components │ ├── hooks/ # custom hooks │ ├── assets/ # images, styles │ ├── App.jsx # root component │ └── main.jsx # entry: mounts App into the DOM ├── index.html # single HTML page React renders into ├── package.json # dependencies and scripts └── vite.config.js # build tool configuration
  • index.html : React is a Single Page Application (SPA): there is one HTML file with a single <div id="root">, and React renders the entire app inside it.
  • main.jsx : The entry point that attaches the root App component to that div.
// main.jsx import { createRoot } from "react-dom/client"; import App from "./App.jsx"; createRoot(document.getElementById("root")).render(<App />);

JSX

JSX (JavaScript XML) lets you write HTML-like markup inside JavaScript. It is not required but is used everywhere in React. A build tool converts JSX into regular JavaScript function calls before it reaches the browser.

  • Expressions in Braces : Put any JavaScript expression inside { }, such as a variable or a calculation.
  • One Root Element : A component must return a single parent element. Use a fragment <>...</> to group siblings without adding an extra DOM node.
  • Attribute Names : Use className instead of class, and camelCase for others (onClick, htmlFor).
  • Self-Closing : Tags without children must close themselves, like <img /> and <br />.
const name = "Ada"; const element = ( <> <h1 className="title">Hello, {name}</h1> <p>2 + 2 = {2 + 2}</p> </> );

Components & Props

A component is a reusable piece of UI written as a JavaScript function that returns JSX. Component names must start with a capital letter. Modern React uses function components; older code used class components.

Props -

Props (properties) pass data from a parent component to a child, like function arguments. They are read-only: a child can never change its own props. This one-way flow keeps data predictable.

// child component function Greeting({ name, age }) { return <p>{name} is {age} years old</p>; } // parent passes props function App() { return <Greeting name="Ada" age={36} />; }
  • children : The special children prop holds whatever a component wraps: <Card>content here</Card>.
  • Composition : Build complex UIs by nesting small components rather than writing one large one.
  • Default & Destructuring : Destructure props in the parameter list and set defaults: function Btn({ label = "OK" }).

State & Events

State is data that a component owns and can change over time. When state changes, React re-renders the component to reflect the new value. State is created with the useState hook.

import { useState } from "react"; function Counter() { const [count, setCount] = useState(0); // [value, setter] return ( <button onClick={() => setCount(count + 1)}> Clicked {count} times </button> ); }
  • Never Mutate Directly : Do not change state variables in place; always call the setter (setCount), or React will not re-render.
  • Updates Are Async : When the new value depends on the old one, use the function form: setCount(c => c + 1).
  • Props vs State : Props come from the parent and are read-only; state is owned by the component and is changeable.
  • Events : Handle user actions with camelCase props like onClick, onChange, and onSubmit, passing a function (not calling it).
  • Lifting State Up : When two components need the same data, move the state to their closest common parent and pass it down as props.

Conditional & List Rendering

Conditional Rendering -

Show different UI based on a condition using normal JavaScript inside JSX.

{isLoggedIn ? <Dashboard /> : <Login />} // ternary {hasError && <p>Something went wrong</p>} // render if true
List Rendering -

Render an array of items with .map(), returning a component for each. Each item needs a unique key prop so React can track which items changed, were added, or removed. Use a stable id, not the array index, when the list can reorder.

const users = [{ id: 1, name: "Ada" }, { id: 2, name: "Alan" }]; function UserList() { return ( <ul> {users.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> ); }

Hooks

Hooks are functions that let function components use React features like state and lifecycle. They must be called at the top level of a component, never inside loops or conditions, and their names start with use.

  • useState : Adds local state to a component. Returns the current value and a setter.
  • useEffect : Runs side effects (data fetching, subscriptions, timers) after render. The dependency array controls when it re-runs.
  • useContext : Reads a shared value from a Context without passing props through every level.
  • useRef : Holds a mutable value that persists across renders without causing a re-render; often used to access a DOM element.
  • useMemo : Caches the result of an expensive calculation so it only recomputes when its dependencies change.
  • useCallback : Caches a function so it is not recreated on every render, useful when passing callbacks to optimized children.
  • useReducer : Manages complex state with a reducer function, an alternative to useState for related state transitions.
  • Custom Hooks : Your own useSomething functions that reuse stateful logic across components.
import { useState, useEffect } from "react"; function Timer() { const [seconds, setSeconds] = useState(0); useEffect(() => { const id = setInterval(() => setSeconds(s => s + 1), 1000); return () => clearInterval(id); // cleanup on unmount }, []); // [] = run once after first render return <p>{seconds}s</p>; }
  • Dependency Array : [] runs the effect once; [value] runs it whenever value changes; omitting it runs after every render.
  • Cleanup : Returning a function from useEffect cleans up (clears timers, removes listeners) before the next run or when the component unmounts.

Forms

React forms are usually controlled: the input's value is tied to state, so React is the single source of truth. Every keystroke updates state through onChange.

function LoginForm() { const [email, setEmail] = useState(""); function handleSubmit(e) { e.preventDefault(); // stop page reload console.log(email); } return ( <form onSubmit={handleSubmit}> <input value={email} onChange={e => setEmail(e.target.value)} /> <button type="submit">Login</button> </form> ); }
  • Controlled Component : The input shows value from state and updates state on change, keeping them in sync.
  • preventDefault : Stops the browser's default form submission (a full page reload).
  • Form Libraries : React Hook Form and Formik handle validation and complex forms with less code.

Routing & Data

React itself has no built-in routing or data fetching; these come from separate libraries, since React is only the view layer.

Routing -

React Router is the standard for navigation. It maps URLs to components without reloading the page, keeping the single-page-app experience.

import { BrowserRouter, Routes, Route, Link } from "react-router-dom"; <BrowserRouter> <nav><Link to="/about">About</Link></nav> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> </Routes> </BrowserRouter>
Data Fetching -
  • fetch / axios : Call APIs inside useEffect and store the result in state.
  • TanStack Query (React Query) : Handles fetching, caching, loading and error states, and refetching automatically. The standard for server data.
  • SWR : A lighter alternative for data fetching with caching.
useEffect(() => { fetch("/api/users") .then(res => res.json()) .then(data => setUsers(data)); }, []);

State Management

Local state (useState) works within a component, but sharing state across many components can lead to "prop drilling" (passing props through many layers). Several tools solve this at the app level.

  • Context API : Built into React. Provides a value to a whole subtree without prop drilling. Best for low-frequency global data like theme, language, or the current user.
  • Redux (Redux Toolkit) : A predictable central store for large apps, with a strict update pattern. Redux Toolkit is the modern, less-boilerplate way to use it.
  • Zustand : A tiny, simple store with minimal boilerplate, popular for small to medium apps.
  • Jotai / Recoil : Atom-based state, breaking global state into small independent pieces.
// Context basics const ThemeContext = createContext("light"); // provide <ThemeContext.Provider value="dark"> <App /> </ThemeContext.Provider> // consume const theme = useContext(ThemeContext);

Ecosystem & Uses

Because React is only the view layer, real apps combine it with tools from its large ecosystem.

Common Ecosystem -
  • Meta-Frameworks : Next.js and Remix add routing, server-side rendering, and a backend around React for full production websites.
  • Styling : Tailwind CSS, CSS Modules, styled-components, and component libraries like Material UI and shadcn/ui.
  • Mobile : React Native builds native iOS and Android apps using the same React concepts.
  • Testing : Vitest or Jest with React Testing Library.
  • Build Tools : Vite (default) or the older Create React App.
What React Is Used For -
  • Single Page Applications : Dashboards, admin panels, and web apps that update without full page reloads.
  • Interactive UIs : Anything with lots of dynamic, changing content driven by user actions.
  • Full Websites : With Next.js, marketing sites and e-commerce that also need SEO and server rendering.
  • Cross-Platform : Mobile apps via React Native, sharing skills and logic with the web.
React vs Others -

React is a flexible library you assemble with other tools. Angular is a complete, opinionated framework with routing and more built in. Vue sits in between, approachable with a gentle learning curve. React has the largest ecosystem and job market of the three.