React Cheatsheet

Basics

Use this React reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

React Cheatsheet

React is a JavaScript library for building UIs as a tree of components. It re-renders components when their state changes and reconciles the result with the real DOM. This page covers setup, JSX rules, and the core mental model; the rest of the sheet covers hooks, forms, context, and patterns in depth.

  • JSX — syntax extension that looks like HTML, compiles to React.createElement() calls.
  • Component — a function (or class) that returns JSX.
  • State — local mutable data; changes trigger re-renders.
  • Props — immutable inputs passed from parent to child.
  • Hooks — functions (use*) that let function components tap into React features.

Installation and Setup

// Create a new project (Vite — recommended)
// npm create vite@latest my-app -- --template react
// cd my-app && npm install && npm run dev

// Or Next.js (full-stack / SSR)
// npx create-next-app@latest my-app

Minimal HTML entry point (Vite/CRA pattern):

// index.html
// <div id="root"></div>

// main.jsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>
);

Required Imports

import React from 'react';                  // needed pre-React 17 for JSX transform
import { useState, useEffect, useRef,
         useContext, useMemo, useCallback,
         useReducer, useId } from 'react';  // hooks — import individually
import { createRoot } from 'react-dom/client'; // rendering

With the new JSX transform (React 17+, Vite, Next.js), you do NOT need import React from 'react' in every file.

JSX Rules

// 1. Return a single root element — wrap siblings in a Fragment
function Example() {
  return (
    <>
      <h1>Hello</h1>
      <p>World</p>
    </>
  );
}

// 2. Close every tag (even self-closing)
const el = <img src="logo.png" alt="logo" />;
const br = <br />;

// 3. Use className, not class
const card = <div className="card" />;

// 4. Use htmlFor, not for
const label = <label htmlFor="email">Email</label>;

// 5. Expressions go in { }
const name = 'Alice';
const greeting = <p>Hello, {name}!</p>;
const sum = <span>{2 + 2}</span>;

// 6. style takes an object with camelCase keys
const style = { backgroundColor: '#fff', fontSize: 16 };
const div = <div style={style} />;

// 7. Boolean attributes
const btn = <button disabled>Click</button>;           // disabled={true}
const btn2 = <button disabled={false}>Click</button>;  // attribute omitted

// 8. Comments inside JSX
const x = (
  <div>
    {/* this is a JSX comment */}
    <p>content</p>
  </div>
);

Component Basics

// Function component — the standard
function Greeting({ name }) {
  return <h1>Hello, {name}!</h1>;
}

// Arrow function variant
const Greeting = ({ name }) => <h1>Hello, {name}!</h1>;

// Default export
export default function App() {
  return <Greeting name="Alice" />;
}

// Named export
export function Header() {
  return <header>...</header>;
}

Component names must start with a capital letter. <button> is the HTML element; <Button> is your component.

Rendering

// Render to DOM
const root = createRoot(document.getElementById('root'));
root.render(<App />);

// Unmount
root.unmount();

StrictMode — double-invokes render functions and effects in development to surface bugs. Has no effect in production.

import { StrictMode } from 'react';
root.render(<StrictMode><App /></StrictMode>);

File and Module Conventions

// One component per file (convention)
// File name matches component name: Button.jsx → export default Button

// Re-export barrel
// components/index.js
export { default as Button } from './Button';
export { default as Card } from './Card';

// Usage
import { Button, Card } from './components';

Key Concepts: Immutability and Re-renders

  • React does not mutate state directly — always return new objects/arrays.
  • A component re-renders when its state changes, its props change, or its parent re-renders.
  • Re-renders are cheap (virtual DOM diffing); avoid premature optimization.
// BAD — mutates state directly
state.count += 1;          // React won't detect this
arr.push(item);

// GOOD — create new values
setState(prev => prev + 1);
setArr(prev => [...prev, item]);

Modern React at a Glance (React 18 → 19)

APISincePurpose
createRoot18Concurrent rendering root (replaces ReactDOM.render)
startTransition / useTransition18Mark updates as non-urgent
useDeferredValue18Defer an expensive derived value
<Suspense>18Show a fallback while children load / lazy-load
use(promise) / use(Context)19Read a promise or context during render (conditionals allowed)
Actions — <form action={fn}>19First-party async form handling (see Forms)
useActionState19State + pending flag wrapped around an action (see Forms)
useFormStatus19Read the enclosing form's pending status (see Forms)
useOptimistic19Show an optimistic value while an action is in flight (see Forms)
ref as a prop19Function components receive ref directly — forwardRef no longer needed
Ref callback cleanup19A ref callback may return a cleanup function
<Context value={…}>19Render a context directly as its provider (see Context)

Removed in React 19: propTypes and defaultProps on function components, string refs, legacy context, ReactDOM.render / ReactDOM.hydrate.

// React 19: ref callbacks can return a cleanup function
<canvas
  ref={(node) => {
    const chart = drawChart(node);
    return () => chart.destroy();   // runs when the node unmounts
  }}
/>