RE

React Cheat Sheet

React reference with hooks, component patterns, event handling, performance optimization, and state management. Copy-ready JSX examples.

52 entries 9 sections

Components

Syntax Description Example
Function component function App() { return <h1>Hello</h1> }
Default export component export default function Home() { ... }
Arrow function component const Button = () => <button>Click</button>
Render component with props <UserCard name='Alice' age={30} />
Render nested content function Layout({ children }) { return <main>{children}</main> }
Fragment (no extra DOM node) <><h1>Title</h1><p>Body</p></>
Conditional rendering isLoggedIn && <Dashboard />
Ternary rendering loading ? <Spinner /> : <Content />
Render list of components users.map(u => <UserCard key={u.id} user={u} />)
Unique key for list items items.map(item => <li key={item.id}>{item.name}</li>)

State Hooks

Syntax Description Example
State variable with setter const [count, setCount] = useState(0)
Lazy initial state const [data, setData] = useState(() => expensiveCalc())
Replace state value setCount(5)
Update based on previous state setCount(prev => prev + 1)
Complex state logic with dispatch const [state, dispatch] = useReducer(reducer, { count: 0 })

Effect Hooks

Syntax Description Example
Run once on mount useEffect(() => { fetchData() }, [])
Run when dependency changes useEffect(() => { search(query) }, [query])
Cleanup on unmount useEffect(() => { const id = setInterval(...); return () => clearInterval(id) }, [])
Synchronous effect (before paint) useLayoutEffect(() => { measureDOM() }, [])

Performance

Syntax Description Example
Memoize computed value const sorted = useMemo(() => items.sort(), [items])
Memoize function reference const handleClick = useCallback(() => { ... }, [id])
Skip re-render if props unchanged const MemoCard = React.memo(Card)
Lazy load component const Page = React.lazy(() => import('./Page'))
Show fallback while loading <Suspense fallback={<Spinner />}><Page /></Suspense>
Mark state update as non-urgent const [isPending, startTransition] = useTransition()
Defer re-rendering of value const deferredQuery = useDeferredValue(query)

Refs & Context

Syntax Description Example
Mutable ref (persists across renders) const inputRef = useRef<HTMLInputElement>(null)
Access ref value inputRef.current?.focus()
Create context const ThemeContext = createContext('light')
Provide context value <ThemeContext.Provider value={theme}>
Consume context value const theme = useContext(ThemeContext)
Forward ref to child component const Input = forwardRef((props, ref) => <input ref={ref} />)
Expose custom ref methods useImperativeHandle(ref, () => ({ focus: () => ... }))

Custom Hooks

Syntax Description Example
Custom hook (starts with 'use') function useWindowSize() { const [size, setSize] = useState(...); ... return size }
Generate unique ID for accessibility const id = useId() → ':r1:'
Subscribe to external store const width = useSyncExternalStore(subscribe, getSnapshot)

Events

Syntax Description Example
Click event handler <button onClick={() => setCount(c => c+1)}>Click</button>
Input change handler <input onChange={(e) => setValue(e.target.value)} />
Form submit handler <form onSubmit={(e) => { e.preventDefault(); ... }}>
Keyboard event handlers <input onKeyDown={(e) => { if (e.key === 'Enter') ... }} />
Focus/blur event handlers <input onFocus={() => setActive(true)} />
Prevent default browser behavior const handleSubmit = (e) => { e.preventDefault() }
Stop event bubbling <div onClick={outer}><button onClick={(e) => { e.stopPropagation() }}>Click</button></div>

Styling

Syntax Description Example
CSS class (not 'class') <div className='container mx-auto'>
Inline styles (camelCase) <div style={{ backgroundColor: 'red', padding: 16 }}>
Conditional classes (with clsx/cn) <div className={cn('btn', isActive && 'btn-active')}>

Patterns

Syntax Description Example
Spread props to child <Button {...buttonProps} />
Iterate over children React.Children.map(children, child => ...)
Clone element with extra props React.cloneElement(child, { onClick: handler })
Function as child for flexibility <DataProvider>{(data) => <Display data={data} />}</DataProvider>
Higher-order component wrapper const Enhanced = withAuth(Dashboard)
Related components sharing state <Tabs><Tabs.List><Tabs.Tab>A</Tabs.Tab></Tabs.List></Tabs>

Frequently asked questions

When should I use useState vs useReducer?

Use useState for simple, independent state values (toggle, counter, input). Use useReducer when: state logic is complex, multiple values are related, next state depends on previous state, or you want to centralize state transitions. useReducer is also better for testing.

What causes unnecessary re-renders?

Components re-render when: state changes, parent re-renders, or context value changes. Common causes: creating new objects/arrays/functions in render (use useMemo/useCallback), not memoizing context values, or updating state too high in the tree.

How do I fetch data in React?

Use useEffect with an async function for simple cases, or a library like TanStack Query for caching, loading states, and refetching. Never make useEffect itself async - define an async function inside it and call it. Handle loading and error states.

What's the difference between useEffect and useLayoutEffect?

useEffect runs asynchronously after the browser paints. useLayoutEffect runs synchronously before the paint. Use useLayoutEffect only when you need to measure or modify the DOM before the user sees it (tooltips, measurements, scroll position).

Should I use Context or a state management library?

Context is great for infrequently-changing values (theme, auth, locale). For frequently-changing values (form state, real-time data), Context causes re-renders in all consumers. Use Zustand, Jotai, or TanStack Query for high-frequency state.

How do I prevent a component from re-rendering?

Wrap it in React.memo() - it skips re-render if props haven't changed. Ensure you're not passing new object/array/function references each render (use useMemo/useCallback). For context, split providers or use selectors.

Go from reference to real skills

Cheat sheets are great for quick lookups. Our in-depth courses take you from the fundamentals to professional-level mastery.

Browse all courses