Skip to main content
Frontend Engineering

React 19 & Modern Hooks

Essential

useState, useEffect, useMemo, useCallback, useRef, useOptimistic, useActionState, and Server Components vs Client Components.

Instant Copy & SearchProduction Flagged SyntaxCurrent Flag Reference

React 19 & Modern Hooks Interactive Command Directory

Browse, search, and copy battle-tested commands & syntax recipes (16 Total Commands).

16+ Verified Recipes
State HookuseState()
const [count, setCount] = useState<number>(0);

Declare state variable with strict TypeScript type and updater function.

Side EffectsuseEffect()
useEffect(() => { const handler = () => setOnline(navigator.onLine); window.addEventListener('online', handler); return () => window.removeEventListener('online', handler); }, []);

Execute side effect with explicit cleanup function on component unmount.

MemoizationuseMemo()
const filteredItems = useMemo(() => items.filter(i => i.score > min), [items, min]);

Cache expensive calculation result between re-renders until dependencies change.

Callback MemoizationuseCallback()
const handleDelete = useCallback((id: string) => { dispatch({ type: 'delete', payload: id }); }, [dispatch]);

Retain stable function reference to prevent unnecessary child re-renders.

DOM & Mutable RefsuseRef()
const inputRef = useRef<HTMLInputElement>(null); const focus = () => inputRef.current?.focus();

Directly access a rendered DOM node or persist mutable value across renders.

React 19 Optimistic UpdatesuseOptimistic()
const [optimisticMessages, setOptimisticMessages] = useOptimistic( messages, (state, newMsg) => [...state, { ...newMsg, sending: true }] );

Display immediate UI feedback before asynchronous server mutation completes.

Unique IdentifiersuseId()
const id = useId();

Generate unique hydration-safe IDs for accessibility labels and input pairing.

Concurrent TransitionsuseTransition
const [isPending, startTransition] = useTransition(); startTransition(() => { setSearchQuery(query); });

Mark state updates as non-urgent transitions allowing immediate typing and UI responsiveness.

Deferred ValuesuseDeferredValue
const deferredSearch = useDeferredValue(searchTerm);

Defer updating expensive rendered subtrees until urgent input keystrokes are rendered.

Action State HooksuseActionState
const [state, formAction, isPending] = useActionState(submitAction, initialState);

React 19 native action hook handling server action responses, errors, and pending state.

Promise Unwrappinguse()
const data = use(fetchPromise);

React 19 use() hook reading Promises and Context conditionally inside component bodies.

Imperative HandlesuseImperativeHandle
useImperativeHandle(ref, () => ({ focus: () => inputRef.current?.focus(), reset: () => setValue('') }));

Expose selective imperative methods to parent components via forwarded refs.

DOM MeasurementuseLayoutEffect
useLayoutEffect(() => { const rect = ref.current.getBoundingClientRect(); setHeight(rect.height); }, []);

Synchronously read DOM layout before browser paint to prevent visual flickering.

Context APIcreateContext, useContext
const ThemeContext = createContext<Theme>('light'); const theme = useContext(ThemeContext);

Pass data through the component tree without manually passing props down through every level.

Error BoundariesgetDerivedStateFromError
class ErrorBoundary extends React.Component { static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(err, info) { logError(err, info); } }

Catch JavaScript rendering errors in child components and display fallback UI gracefully.

Code Splittinglazy, Suspense
const HeavyChart = lazy(() => import('./HeavyChart')); <Suspense fallback={<Skeleton />}> <HeavyChart /> </Suspense>

Dynamically load component bundles on demand wrapped with Suspense fallback skeletons.

Zero Setup100% In-Browser Execution

Companion Developer Tools & Playgrounds

Accelerate command execution and syntax debugging with HelloAIHub suite of interactive tools.

Explore all developer tools

React 19 & Modern Hooks: Command Groups & Quick Index

16 indexed entries across 16 sections
State Hook1 items
Side Effects1 items
Memoization1 items
Callback Memoization1 items
DOM & Mutable Refs1 items
React 19 Optimistic Updates1 items
Unique Identifiers1 items
Concurrent Transitions1 items
Deferred Values1 items
Action State Hooks1 items
Promise Unwrapping1 items
Imperative Handles1 items
DOM Measurement1 items
Context API1 items
Error Boundaries1 items
Code Splitting1 items

Highlighted Flags & Syntax Examples in React 19 & Modern Hooks

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

Declare state variable with strict TypeScript type and updater function.

Flags: useState()
useEffect(() => { const handler = () => setOnline(navigator.onLine); window.addEventListener('online', handler); return () => window.removeEventListener('online', handler); }, []);

Execute side effect with explicit cleanup function on component unmount.

Flags: useEffect()
const filteredItems = useMemo(() => items.filter(i => i.score > min), [items, min]);

Cache expensive calculation result between re-renders until dependencies change.

Flags: useMemo()
const handleDelete = useCallback((id: string) => { dispatch({ type: 'delete', payload: id }); }, [dispatch]);

Retain stable function reference to prevent unnecessary child re-renders.

Flags: useCallback()

Frequently Asked Questions

Expert recommendations, common traps, and production best practices for React 19 & Modern Hooks.

What is the difference between React Server Components (RSC) and Client Components?

Server Components execute exclusively on the server at build or request time, emit zero JavaScript to the client bundle, and can directly access databases or internal networks. Client Components ('use client') run on the client, receive hydrated interactivity, and support useState, useEffect, and DOM events.

Why should keys not be array indices in React lists?

Using indices as keys breaks component state and causes rendering bugs when items are inserted, deleted, or reordered, because React relies on keys to determine if a specific DOM element should be reused or destroyed.

How does the React Virtual DOM diffing algorithm (Reconciliation) work?

React maintains a virtual representation of the UI in memory. When state updates occur, React generates a new Virtual DOM tree and runs a heuristic O(n) diffing algorithm comparing it against the previous tree. It assumes different element types produce different trees, and uses unique 'key' props to match and reorder child elements efficiently, minimizing real DOM mutations.

What is the difference between useEffect and useLayoutEffect?

'useEffect' runs asynchronously after the browser has completed layout and painted the screen, making it ideal for data fetching and side effects that do not alter layout. 'useLayoutEffect' fires synchronously immediately after DOM mutations but before the browser paints the screen, making it necessary for measuring element dimensions and preventing layout shift flickers.

How does React 18/19 Concurrent Mode and automatic batching work?

Concurrent Mode allows React to interrupt, pause, or abandon in-progress renders to respond to urgent user input (like clicks or typing). Automatic batching consolidates multiple state updates inside promises, setTimeout, and event handlers into a single re-render, reducing rendering overhead.

What are React 19 Actions and how does useActionState simplify forms?

React 19 Actions are async functions passed to form 'action' attributes. React automatically manages pending states, optimistic updates, and error handling. 'useActionState' binds directly to actions, returning the returned state payload, the dispatcher function, and a boolean 'isPending' indicator without manual useState plumbing.

Cross-Hub Skill Acceleration

Combine command lookups with active coding interviews and complete career paths.

Need More Cheat Sheets?

Explore developer cheat sheets and syntax guides on HelloAIHub.

Browse All Cheat Sheets