React logoReact BEGINNER

React Components & JSX

React components cheat sheet covering JSX syntax, props, conditional rendering, lists, event handling, and composition patterns.

12 min read
reactjsxcomponentspropsconditional-renderinglists

Component Essentials

Core concepts for building React components

Function Components

Modern way to create React components

📄 Codejavascript
🟢 Essential - Use function components for all new code
💡 Component names must start with capital letter
📌 Returns JSX to describe the UI
componentsessential

Basic Props

Pass data to components via props

📄 Codejavascript
🟢 Essential - Props make components reusable
💡 Props are read-only, never modify them
📌 Pass any JavaScript value as a prop
propsessential

Default Props

Set default values for optional props

javascript
💡 Use = in destructuring for clean defaults
📌 Default values only used if prop is undefined
⚡ Defaults make components more flexible
propsdefaults

Children Prop

Pass JSX content between component tags

📄 Codejavascript
🟢 Essential - Children enables component composition
💡 Anything between tags becomes children prop
📌 Can be text, elements, or other components
propschildrencomposition

Event Handlers

Handle user interactions with events

📄 Codejavascript
🟢 Essential - Events enable interactivity
💡 Use arrow functions to pass parameters
⚠️ Don't call the function: onClick={handleClick} not onClick={handleClick()}
eventshandlersessential

Component Import/Export

Organize components in separate files

javascript
💡 One component per file is common practice
📌 Use default export for main component
⚡ Named exports for utility components
importexportmodules

Keeping Components Pure

Components must be pure functions of their props and state

jsx
💡 Pure components are predictable, easier to test, and enable React optimizations
⚡ React assumes components are pure — breaking this rule causes subtle bugs
📌 Side effects belong in event handlers or useEffect, never in render
🟢 StrictMode double-renders in dev to catch impure components early
purerenderside-effects

JSX Fundamentals

JavaScript XML syntax for describing UI in React

JSX Basics

JavaScript XML syntax for React

📄 Codejavascript
🟢 Essential - JSX is JavaScript, not HTML
💡 Use parentheses for multi-line JSX
📌 Must return a single root element
jsxsyntaxessential

JSX Expressions

Embed JavaScript expressions in JSX

📄 Codejavascript
🟢 Essential - Use {} to embed any JS expression
💡 Expressions produce values, statements don't
⚠️ Can't use if/for/while directly, use ternary or map
jsxexpressionsessential

JSX Attributes

HTML attributes in JSX use camelCase

📄 Codejavascript
💡 Use className instead of class
📌 Use htmlFor instead of for
⚡ All attributes use camelCase naming
jsxattributes

Inline Styles

Apply styles using JavaScript objects

📄 Codejavascript
💡 Style attribute takes an object, not string
📌 Use camelCase for CSS properties
⚡ Values are strings or numbers (px assumed)
jsxstylescss

Conditional Rendering

Show/hide elements based on conditions

📄 Codejavascript
🟢 Essential - && shows element if condition is true
💡 Ternary (? :) for if-else rendering
⚠️ Remember: 0 and empty string render, null/undefined don't
jsxconditionalessential

Lists & Keys

Render arrays with map and unique keys

javascript
🟢 Essential - Always include key prop in lists
💡 Keys help React track changes efficiently
⚠️ Keys must be unique among siblings
jsxlistskeysessential

Fragments

Return multiple elements without wrapper

📄 Codejavascript
💡 Fragments avoid extra wrapper divs
📌 Use <> </> shorthand in most cases
⚡ Only Fragment accepts key prop
jsxfragments

JSX Comments

Add comments in JSX code

📄 Codejavascript
💡 JSX comments must be inside {/* */}
📌 Regular // comments work outside JSX
⚡ Comments don't appear in rendered HTML
jsxcomments

Forms & Controlled Components

Build interactive forms with controlled and uncontrolled components

Controlled Inputs

Form inputs controlled by React state

📄 Codejavascript
🟢 Essential - React controls the input value
💡 Value comes from state, onChange updates state
📌 Single source of truth for form data
formscontrolledessential

Form Submission

Handle form submit events

📄 Codejavascript
⚠️ Always preventDefault() on form submit
💡 Form validates before onSubmit fires
📌 Button type="submit" triggers form submission
formssubmit

Select & Textarea

Controlled select dropdowns and textareas

📄 Codejavascript
💡 Select uses value prop, not selected attribute
📌 Textarea uses value prop, not children
⚡ Same pattern as input elements
formsselecttextarea

Checkboxes & Radio

Handle checkbox and radio button inputs

📄 Codejavascript
💡 Checkbox uses checked prop and e.target.checked
📌 Radio buttons share same state variable
⚡ Name attribute groups radio buttons
formscheckboxradio

Context API

Share data across components without prop drilling

Context API

Create, provide, and consume context with createContext and useContext

jsx
💡 Context is for data many components need — theme, auth, locale, language
⚡ Wrap useContext in a custom hook (useTheme) for type safety and better errors
📌 Every consumer re-renders when the Provider value changes — split contexts to limit re-renders
🟢 React 19+ lets you use <Context value={...}> directly without .Provider
contextproviderusecontext

Component Patterns & Types

Advanced patterns for type safety and component composition

Composition with children

Use the children prop to build flexible, composable layout components

jsx
💡 Composition is React favorite pattern — solves most "inheritance" needs cleanly
⚡ Use named slot props (header, sidebar) when you need multiple "children" areas
📌 Composition avoids prop drilling without needing Context for layout components
🟢 Function-as-children gives the parent control while letting children access internal data
compositionchildrenslots

PropTypes & TypeScript

Add type checking to React components

typescript
⚛️ PropTypes for runtime checking, TypeScript for compile-time
💡 TypeScript provides better IDE support and refactoring
📌 Use discriminated unions for component variants
⚠️ PropTypes only work in development mode
⚡ Generic components provide type safety with flexibility

Refs & forwardRef

Access DOM elements and pass refs through components

javascript
⚛️ Refs provide access to DOM elements imperatively
💡 Use forwardRef to pass refs through components
📌 Refs persist values between renders without causing re-render
⚠️ Don't overuse refs - prefer declarative React patterns
⚡ Callback refs useful for dynamic ref management

Compound Components

Build flexible APIs with related components that share state

jsx
💡 Compound components give consumers full control over markup while sharing state
⚡ Used by libraries like Radix UI, shadcn/ui, and React Aria for flexible primitives
📌 Attach children as static properties (Tabs.Tab) for a clean discoverable API
🟢 Internal Context shares state without exposing it as props on every child
compoundpatterncontext

Higher-Order Components (HOCs)

Functions that take a component and return an enhanced component

jsx
💡 HOCs are functions that wrap a component to add behavior — common in legacy code
⚡ Modern React prefers custom hooks over HOCs for sharing logic
📌 Always spread {...props} to forward unrelated props to the wrapped component
🟢 HOCs are still useful for cross-cutting concerns like auth guards and analytics
hocpatterncomposition

Render Props

Share logic by passing a render function as a prop

jsx
💡 Render props let a component share state/logic while letting consumers control rendering
⚡ Modern React replaces most render props with custom hooks for cleaner JSX
📌 Render props are still useful when you need access to the component lifecycle in JSX
🟢 Children-as-function is a render prop variant — same idea, cleaner syntax
render-propspattern

Optimization & Advanced Features

Performance optimization and advanced React features

Suspense & lazy()

Code-split components and show fallback UI while loading

jsx
💡 lazy() splits the component into its own JS bundle — only loaded when rendered
⚡ Use multiple Suspense boundaries to load page sections independently
📌 Route-level code splitting is the biggest bundle-size win for most apps
🟢 Suspense also works with data fetching libraries that support it (Relay, React Query)
suspenselazycode-splitting

Error Boundaries

Catch render errors in child components and show fallback UI

jsx
💡 Error boundaries must be class components — there is no hook equivalent (yet)
⚡ Use react-error-boundary library for a cleaner functional API
📌 Wrap risky subtrees independently so one error doesn't take down the whole app
🟢 Error boundaries do NOT catch async errors or event handler errors — use try/catch there
error-boundaryerrorclass

React.memo & Optimization

Optimize component re-renders with memoization

javascript
⚛️ React.memo prevents re-renders when props haven't changed
💡 Use useMemo for expensive computations
📌 useCallback for stable function references
⚠️ Premature optimization can hurt maintainability
⚡ Profile first to identify actual performance issues

Styling Components

Different approaches to styling React components

javascript
⚛️ Choose styling approach based on project needs
💡 CSS Modules provide scoped styles without runtime cost
📌 CSS-in-JS offers dynamic styling with JS power
⚠️ Inline styles can't use pseudo-classes or media queries
⚡ Utility-first CSS (Tailwind) for rapid development

Portals (createPortal)

Render children into a different DOM node outside the parent hierarchy

jsx
💡 Portals render into any DOM node but stay in the React tree — events bubble normally
⚡ Use portals for modals, tooltips, dropdowns — anything that needs to escape overflow:hidden
📌 Even though the DOM node is elsewhere, Context, refs, and events all work as expected
🟢 Stop click propagation on the inner content to prevent overlay clicks from closing the modal
portalmodaltooltip

StrictMode

Catch bugs early by enabling extra development checks

jsx
💡 StrictMode runs in dev only — no production impact, no perf cost
⚡ Double-rendering surfaces impure components and missing cleanup early
📌 If your console.log fires twice in dev, that's StrictMode catching a side effect
🟢 You can wrap individual subtrees in StrictMode for gradual adoption
strict-modedevdebugging