📖 Guide

React Hooks Reference

Complete React Hooks reference — useState, useEffect, useContext, custom hooks, and common patterns.

81 commands across 12 categories

useState

CommandDescription
const [count, setCount] = useState(0)
Initialize state with a value
const [name, setName] = useState("")
Initialize state with a string
const [user, setUser] = useState<User | null>(null)
Initialize state with explicit type (TypeScript)
const [items, setItems] = useState<string[]>([])
Initialize state with typed empty array
setCount(5)
Set state to a specific value
setCount(prev => prev + 1)
Update state based on previous value (functional update)
setItems(prev => [...prev, newItem])
Add item to array state
setItems(prev => prev.filter(i => i.id !== id))
Remove item from array state
setUser(prev => ({ ...prev, name: "new" }))
Update a property in object state
const [state, setState] = useState(() => expensiveComputation())
Lazy initialization — function runs only on first render

useEffect

CommandDescription
useEffect(() => { /* runs after every render */ })
Effect with no dependency array — runs after every render
useEffect(() => { /* runs once */ }, [])
Effect with empty deps — runs only on mount
useEffect(() => { /* runs when count changes */ }, [count])
Effect with dependencies — runs when specified values change
useEffect(() => { return () => { /* cleanup */ } }, [])
Cleanup function — runs on unmount or before re-running effect
useEffect(() => { const sub = api.subscribe(handler); return () => sub.unsubscribe(); }, [])
Subscribe/unsubscribe pattern
useEffect(() => { const controller = new AbortController(); fetch(url, { signal: controller.signal }); return () => controller.abort(); }, [url])
Fetch with abort cleanup — prevent state updates on unmounted component
useEffect(() => { const timer = setInterval(tick, 1000); return () => clearInterval(timer); }, [])
Timer with cleanup
useEffect(() => { document.title = `Count: ${count}`; }, [count])
Sync document title with state
useEffect(() => { const handler = (e: KeyboardEvent) => { /* ... */ }; window.addEventListener("keydown", handler); return () => window.removeEventListener("keydown", handler); }, [])
Add/remove event listener

useContext

CommandDescription
const ThemeContext = createContext<"light" | "dark">("light")
Create a context with a default value
const UserContext = createContext<User | null>(null)
Create a context with nullable default
<ThemeContext.Provider value={theme}>{children}</ThemeContext.Provider>
Provide context value to children
const theme = useContext(ThemeContext)
Consume context value in a component
function useTheme() { const ctx = useContext(ThemeContext); if (!ctx) throw new Error("Must be in ThemeProvider"); return ctx }
Custom hook with context validation
const AuthContext = createContext<{ user: User; login: () => void } | undefined>(undefined)
Context with actions and state
function AuthProvider({ children }: { children: React.ReactNode }) { const [user, setUser] = useState<User | null>(null); return <AuthContext.Provider value={{ user, login }}>{children}</AuthContext.Provider>; }
Provider component pattern with state

useReducer

CommandDescription
const [state, dispatch] = useReducer(reducer, initialState)
Initialize useReducer with a reducer function and initial state
type Action = { type: "increment" } | { type: "decrement" } | { type: "set"; payload: number }
Define action types with discriminated union
function reducer(state: State, action: Action): State { switch (action.type) { case "increment": return { count: state.count + 1 }; case "decrement": return { count: state.count - 1 }; default: return state; } }
Reducer function with switch statement
dispatch({ type: "increment" })
Dispatch an action
dispatch({ type: "set", payload: 42 })
Dispatch an action with payload
const [state, dispatch] = useReducer(reducer, arg, init)
Lazy initialization — init function transforms arg into initial state
const [todos, dispatch] = useReducer(todosReducer, [])
Manage a list with useReducer

useCallback

CommandDescription
const handleClick = useCallback(() => { setCount(c => c + 1) }, [])
Memoize a callback with no dependencies
const handleChange = useCallback((e: ChangeEvent<HTMLInputElement>) => { setName(e.target.value) }, [])
Memoize an event handler
const fetchData = useCallback(async () => { const res = await fetch(url); setData(await res.json()) }, [url])
Memoize async function — re-creates when url changes
const handleSubmit = useCallback((data: FormData) => { api.submit(id, data) }, [id])
Memoize callback that depends on a prop
<ChildComponent onClick={handleClick} />
Pass memoized callback to prevent child re-renders
const fn = useCallback(handler, deps) // equivalent to: const fn = useMemo(() => handler, deps)
useCallback is shorthand for useMemo returning a function

useMemo

CommandDescription
const sorted = useMemo(() => items.sort((a, b) => a - b), [items])
Memoize expensive computation
const filtered = useMemo(() => items.filter(i => i.includes(query)), [items, query])
Memoize filtered list — recalculates when items or query change
const chartData = useMemo(() => processData(rawData), [rawData])
Memoize data transformation
const style = useMemo(() => ({ color: dark ? "white" : "black" }), [dark])
Memoize object to maintain referential equality
const Component = useMemo(() => <ExpensiveTree data={data} />, [data])
Memoize JSX element
const value = useMemo(() => ({ state, dispatch }), [state])
Memoize context value to prevent unnecessary re-renders

useRef

CommandDescription
const inputRef = useRef<HTMLInputElement>(null)
Create a ref for a DOM element
<input ref={inputRef} />
Attach ref to a DOM element
inputRef.current?.focus()
Access DOM element via ref
const renderCount = useRef(0)
Create a mutable ref that persists across renders
renderCount.current += 1
Mutate ref value (does not trigger re-render)
const prevValue = useRef(value) useEffect(() => { prevValue.current = value }, [value])
Track previous value pattern
const callbackRef = useRef(callback) useEffect(() => { callbackRef.current = callback })
Store latest callback in ref (avoid stale closures)
const timerRef = useRef<ReturnType<typeof setInterval>>(null)
Store timer/interval ID in ref

useLayoutEffect

CommandDescription
useLayoutEffect(() => { const { height } = ref.current!.getBoundingClientRect(); setHeight(height); }, [dep])
Measure DOM before browser paint — prevents visual flicker
useLayoutEffect(() => { ref.current!.style.transform = `translateX(${x}px)`; }, [x])
Synchronously update DOM position
useLayoutEffect(() => { const el = ref.current!; el.scrollTop = el.scrollHeight; }, [messages])
Scroll to bottom before paint
// useLayoutEffect fires synchronously after DOM mutations // but before the browser paints // useEffect fires after paint
Timing: useLayoutEffect vs useEffect

useId

CommandDescription
const id = useId()
Generate a unique ID stable across server/client rendering
<label htmlFor={id}>Name</label> <input id={id} />
Use generated ID for form label-input association
const emailId = useId() const passwordId = useId()
Generate multiple IDs in a component
<div aria-labelledby={id}>
Use ID for ARIA attributes

Custom Hooks Patterns

CommandDescription
function useToggle(initial = false) { const [value, setValue] = useState(initial); const toggle = useCallback(() => setValue(v => !v), []); return [value, toggle] as const; }
useToggle — boolean toggle hook
function useLocalStorage<T>(key: string, initial: T) { const [value, setValue] = useState<T>(() => { const stored = localStorage.getItem(key); return stored ? JSON.parse(stored) : initial; }); useEffect(() => { localStorage.setItem(key, JSON.stringify(value)) }, [key, value]); return [value, setValue] as const; }
useLocalStorage — persist state to localStorage
function useDebounce<T>(value: T, delay: number): T { const [debounced, setDebounced] = useState(value); useEffect(() => { const timer = setTimeout(() => setDebounced(value), delay); return () => clearTimeout(timer); }, [value, delay]); return debounced; }
useDebounce — debounce a rapidly changing value
function useFetch<T>(url: string) { const [data, setData] = useState<T | null>(null); const [loading, setLoading] = useState(true); const [error, setError] = useState<Error | null>(null); useEffect(() => { const controller = new AbortController(); fetch(url, { signal: controller.signal }) .then(r => r.json()).then(setData).catch(setError).finally(() => setLoading(false)); return () => controller.abort(); }, [url]); return { data, loading, error }; }
useFetch — data fetching hook with loading/error states
function useMediaQuery(query: string): boolean { const [matches, setMatches] = useState(() => window.matchMedia(query).matches); useEffect(() => { const mql = window.matchMedia(query); const handler = (e: MediaQueryListEvent) => setMatches(e.matches); mql.addEventListener("change", handler); return () => mql.removeEventListener("change", handler); }, [query]); return matches; }
useMediaQuery — responsive design hook
function usePrevious<T>(value: T): T | undefined { const ref = useRef<T>(); useEffect(() => { ref.current = value }); return ref.current; }
usePrevious — track the previous value of a prop/state
function useOnClickOutside(ref: RefObject<HTMLElement>, handler: () => void) { useEffect(() => { const listener = (e: MouseEvent) => { if (!ref.current?.contains(e.target as Node)) handler(); }; document.addEventListener("mousedown", listener); return () => document.removeEventListener("mousedown", listener); }, [ref, handler]); }
useOnClickOutside — detect clicks outside an element
function useInterval(callback: () => void, delay: number | null) { const savedCallback = useRef(callback); useEffect(() => { savedCallback.current = callback }); useEffect(() => { if (delay === null) return; const id = setInterval(() => savedCallback.current(), delay); return () => clearInterval(id); }, [delay]); }
useInterval — declarative setInterval hook

Rules of Hooks

CommandDescription
// ✅ Call hooks at the top level of your component
Rule 1: Only call hooks at the top level — not inside loops, conditions, or nested functions
// ❌ if (condition) { useState(0) }
Never call hooks conditionally — React relies on call order being consistent
// ✅ Call hooks from React function components or custom hooks
Rule 2: Only call hooks from React functions — not regular JavaScript functions
// ✅ function useCustom() { useState(0); useEffect(() => {}) }
Custom hooks can call other hooks
// ✅ Name custom hooks starting with "use"
Convention: custom hooks must start with 'use' for linter to enforce rules
// ❌ for (const item of items) { useEffect(() => {}) }
Never call hooks in loops — call count must be identical every render

Common Patterns

CommandDescription
const [state, setState] = useState(initialState) const handleChange = (e: ChangeEvent<HTMLInputElement>) => { setState(prev => ({ ...prev, [e.target.name]: e.target.value })) }
Dynamic form state with computed property names
useEffect(() => { let cancelled = false; async function load() { const data = await fetchData(); if (!cancelled) setData(data); } load(); return () => { cancelled = true }; }, [dep])
Avoid setting state after unmount (race condition)
const [, forceUpdate] = useReducer(x => x + 1, 0)
Force re-render trick (escape hatch)
function useStableCallback<T extends (...args: any[]) => any>(fn: T): T { const ref = useRef(fn); ref.current = fn; return useCallback((...args: any[]) => ref.current(...args), []) as T; }
Stable callback ref — always references latest function without re-creating
const isMounted = useRef(true); useEffect(() => { return () => { isMounted.current = false } }, [])
Track mount status with ref
function useRenderCount() { const count = useRef(0); count.current++; return count.current; }
Debug: count component renders

More Guides

🌿
Git Commands
Complete Git command reference — from basics to advanced workflows. Searchable, with examples.
📝
Vim Commands
Complete Vim/Vi command reference — modes, motions, editing, search, and advanced features.
🐳
Docker Commands
Complete Docker & Docker Compose command reference — containers, images, volumes, networks, and orchestration.
🔤
Regex Reference
Complete regular expression reference — syntax, patterns, quantifiers, groups, lookaheads, and common recipes.
🐧
Linux Commands
Complete Linux/Bash command reference — file management, text processing, networking, system admin, and shell scripting.
☸️
Kubernetes Commands
Complete Kubernetes & kubectl command reference — pods, deployments, services, configmaps, and cluster management.
🐍
Python Reference
Complete Python reference — syntax, data structures, string methods, file I/O, comprehensions, and common patterns.
🗃️
SQL Reference
Complete SQL reference — queries, joins, aggregation, subqueries, indexes, and database management.
🌐
Nginx Reference
Complete Nginx configuration reference — server blocks, locations, proxying, SSL, load balancing, and caching.
🔐
SSH Commands
Complete SSH reference — connections, key management, tunneling, config, SCP/SFTP, and security hardening.
👷
Jenkins Reference
Complete Jenkins reference — pipeline syntax, Jenkinsfile, plugins, CLI, agents, and CI/CD patterns.
📨
HTTP Headers Reference
Complete HTTP headers reference — request headers, response headers, caching, security, CORS, and content negotiation. Searchable, with examples.
🐘
PostgreSQL Reference
Comprehensive PostgreSQL reference — from connection basics to advanced features like JSONB, full-text search, window functions, and performance tuning.
Async Patterns Reference
Multi-language async/concurrency patterns — JavaScript, Python, Go, Rust, Java, and universal concurrency patterns.
📡
Protobuf & gRPC Reference
Comprehensive reference for Protocol Buffers (proto3) and gRPC — message definitions, services, streaming, and common patterns.
📚
JS Array Methods
Complete JavaScript Array methods reference — creating, searching, transforming, sorting, iterating, and common patterns. Searchable, with examples.
🌊
Tailwind CSS Reference
Complete Tailwind CSS reference — layout, spacing, typography, colors, responsive design, states, and common patterns. Searchable, with examples.
GraphQL Reference
Complete GraphQL reference — schema definition, types, queries, mutations, directives, fragments, and common patterns. Searchable, with examples.
💻
VS Code Shortcuts
Complete VS Code keyboard shortcuts — editing, navigation, search, multi-cursor, terminal, debug, and more. Searchable, with Cmd/Ctrl notation.
🔲
CSS Grid Reference
Complete CSS Grid reference — container properties, item placement, grid functions, and common layout patterns. Searchable, with examples.
📦
CSS Flexbox Reference
Complete CSS Flexbox reference — container properties, item properties, and common layout patterns. Searchable, with examples.
🔷
TypeScript Reference
Complete TypeScript reference — types, interfaces, generics, utility types, and advanced patterns. Searchable, with examples.
☁️
AWS CLI Reference
Complete AWS CLI reference — EC2, S3, IAM, Lambda, ECS, RDS, CloudFormation, and common operations.
🐹
Go Reference
Complete Go (Golang) reference — syntax, types, functions, concurrency, error handling, and common patterns.
💠
PowerShell Reference
Complete PowerShell reference — cmdlets, pipelines, scripting, file operations, remote management, and Active Directory.
💾
Redis Commands
Complete Redis command reference — strings, hashes, lists, sets, sorted sets, pub/sub, transactions, and server management.
🏗️
Terraform Commands
Complete Terraform reference — init, plan, apply, state management, modules, workspaces, and HCL syntax.
⚙️
Ansible Commands
Complete Ansible reference — playbooks, modules, inventory, roles, vault, and ad-hoc commands.
🟨
JavaScript
Complete JavaScript reference — variables, types, operators, strings, arrays, objects, functions, async, DOM, ES6+, and more.
🎨
CSS
Complete CSS reference — selectors, box model, positioning, typography, animations, media queries, custom properties, and more.
📄
HTML
Complete HTML reference — document structure, text content, forms, media, semantic elements, accessibility, and more.
Java
Complete Java reference — data types, strings, collections, OOP, interfaces, exceptions, file I/O, streams, lambdas, and more.
💻
Bash
Complete Bash reference — variables, strings, arrays, conditionals, loops, functions, file tests, I/O redirection, process management, and more.
🦀
Rust
Comprehensive Rust language cheat sheet covering ownership, traits, pattern matching, concurrency, and more.
📝
Markdown
Complete Markdown syntax reference for headings, formatting, links, tables, code blocks, and extensions.
📋
YAML
YAML syntax reference covering scalars, collections, anchors, multi-line strings, and common patterns.
🌐
Curl
Curl command-line reference for HTTP requests, authentication, file transfers, debugging, and common API patterns.
Cron
Cron scheduling reference covering syntax, field values, crontab management, and common schedule patterns.
🖥️
Tmux
Terminal multiplexer for managing multiple sessions, windows, and panes from a single terminal.
🔧
Awk
Powerful text processing language for pattern scanning, data extraction, and report generation.
✂️
Sed
Stream editor for filtering and transforming text, line by line.
🔍
Find
Search for files and directories in a directory hierarchy with powerful filtering options.
🔎
Grep
Search text using patterns. Filter lines from files, command output, or streams with regular expressions.
🐘
PHP
Complete PHP cheat sheet covering syntax, OOP, arrays, PDO, and modern PHP 8.x features.
⚙️
C
Complete C programming cheat sheet covering syntax, pointers, memory management, and standard library.
🔷
C++
Complete C++ cheat sheet covering STL containers, OOP, templates, smart pointers, and modern C++ features.
🐬
MySQL
Complete MySQL cheat sheet covering queries, joins, indexes, transactions, and administration.
💅
Sass
Complete Sass/SCSS cheat sheet covering variables, mixins, functions, nesting, and modern module system.
🔐
Chmod
Linux file permission commands and patterns for chmod.
🔢
NumPy
Essential NumPy commands for array manipulation and numerical computing in Python.
🐼
Pandas
Pandas cheat sheet for data manipulation, analysis, and transformation in Python.
🎯
Dart
Dart language cheat sheet covering syntax, types, OOP, null safety, and async patterns.
🔺
Laravel
Laravel PHP framework cheat sheet for routing, Eloquent, Blade, Artisan, and more.
🟩
Node.js
Comprehensive Node.js runtime reference covering modules, file system, HTTP, streams, and more.
Next.js
Next.js App Router reference covering routing, data fetching, server components, and deployment.
🍃
MongoDB
MongoDB reference covering CRUD operations, aggregation, indexes, and administration.
🔥
Firebase
Firebase reference covering Authentication, Firestore, Realtime Database, Cloud Functions, and Hosting.
🐳
Docker Compose
Docker Compose reference covering CLI commands, service configuration, networking, volumes, and more.
💲
jQuery
Quick reference for jQuery selectors, DOM manipulation, events, AJAX, and more.
📐
LaTeX
Quick reference for LaTeX document structure, math mode, formatting, and common packages.
🎯
XPath
Quick reference for XPath expressions, axes, predicates, and functions for XML/HTML querying.
Emmet
Quick reference for Emmet abbreviations for lightning-fast HTML and CSS coding.
📦
TOML
Quick reference for TOML configuration file syntax, types, tables, and common patterns.
💎
Prisma
Complete Prisma ORM cheat sheet — schema, queries, migrations, and CLI.
🤖
GitHub Actions
Complete GitHub Actions cheat sheet — workflows, triggers, jobs, and CI/CD patterns.
📦
npm
Complete npm cheat sheet — package management, scripts, publishing, and configuration.
Supabase
Complete Supabase cheat sheet — auth, database, realtime, storage, and edge functions.
🪶
Apache
Complete Apache HTTP Server cheat sheet — virtual hosts, modules, rewrite rules, and SSL.
📡
HTTP Status Codes
Complete reference of all standard HTTP response status codes with descriptions and use cases.
🔤
ASCII Table
Complete ASCII character reference with decimal, hexadecimal, and character values.
🔧
Chrome DevTools
Essential Chrome DevTools shortcuts, commands, and workflows for web developers.
💧
Drizzle ORM
Complete Drizzle ORM reference for schema definition, queries, relations, migrations, and common patterns.
Vercel CLI
Complete Vercel CLI reference for deployment, project management, domains, environment variables, and configuration.
🔄
PM2
Production process manager for Node.js applications with built-in load balancer, monitoring, and zero-downtime reloads.
📺
Screen
GNU Screen terminal multiplexer for persistent sessions, window management, and remote work.
📦
Webpack
Module bundler for JavaScript applications — loaders, plugins, code splitting, optimization, and dev server.
Vite
Next-generation frontend build tool with instant HMR, native ES modules, and optimized production builds via Rollup.

📖 Free, searchable command reference. Bookmark this page for quick access.