Irbisa · Cheatsheet
State & Events
useState, state as a snapshot, batching, updater functions, immutable updates of objects and arrays, lifting state up, events
What is state in React, and how does
useStatework?type User = { name: string }; function Counter() { const [count, setCount] = useState(0); const [user, setUser] = useState<User | null>(null);…Why does changing a regular local variable not update the screen, while
useStatedoes?How do you handle events in React, and how do you pass an argument to a handler?
type Item = { id: string; title: string }; function TodoList({ items, onRemove }: { items: Item[]; onRemove: (id: string) => void }) { function handleSubmit(e: React.FormEvent<HTMLFormElement>) { e.preventDefault(); // stop the full page reload console.log('submitted');…Find the bug: this component crashes with "Too many re-renders" on its first render.
function Greeting({ name }: { name: string }) { const [upper, setUpper] = useState(''); setUpper(name.toUpperCase()); return <h1>{upper}</h1>;}Why must you update state immutably instead of changing an object or array in place?
How do you update an object, including a nested one, stored in state?
type Person = { name: string; address: { city: string; zip: string } }; function Profile() { const [person, setPerson] = useState<Person>({ name: 'Ada', address: { city: 'London', zip: 'N1' },…Find the bug: typing in the search box resets the category filter to "All".
type Filters = { query?: string; category?: string }; function ProductFilters() { const [filters, setFilters] = useState<Filters>({ category: 'books' }); return ( <> <input value={filters.query ?? ''} onChange={(e) => setFilters({ query: e.target.value })} /> <select value={filters.category ?? ''} onChange={(e) => setFilters({ category: e.target.value })}> <option value="">All</option> <option value="books">Books</option> </select> </> );}How do you add, remove and update items in an array stored in state?
type Todo = { id: number; text: string; done: boolean }; function useTodos(initial: Todo[]) { const [todos, setTodos] = useState(initial); const add = (text: string) =>…What does "lifting state up" mean, and when do you do it?
function Accordion() { const [openIndex, setOpenIndex] = useState(0); // lifted from the panels return ( <> <Panel title="About" isOpen={openIndex === 0} onOpen={() => setOpenIndex(0)} />…What does "state is a snapshot" mean in React?
What is the updater function form of a state setter, and when should you use it?
function Counter() { const [count, setCount] = useState(0); function addThree() { setCount((c) => c + 1); setCount((c) => c + 1);…What does the alert show and what does the button show after one click, and why?
function Counter() { const [number, setNumber] = useState(0); function handleClick() { setNumber(number + 5); setNumber((n) => n + 1); setNumber(number + 1); alert(number); } return <button onClick={handleClick}>{number}</button>;}What is batching in React, and what changed with automatic batching in React 18?
import { flushSync } from 'react-dom'; function Chat() { const [items, setItems] = useState<string[]>([]); const [draft, setDraft] = useState(''); const listRef = useRef<HTMLUListElement>(null);…Find the bug: clicking "Add" does not show the new tag until you type in the input.
function Tags() { const [tags, setTags] = useState<string[]>(['react']); const [text, setText] = useState(''); function handleAdd() { tags.push(text); setTags(tags); } return ( <> <input value={text} onChange={(e) => setText(e.target.value)} /> <button onClick={handleAdd}>Add</button> <p>{tags.join(', ')}</p> </> );}What happens when you call a state setter with the value the state already has?
What is lazy initial state in
useState, and when do you need it?function Notes() { // JSON.parse runs only on the first render const [notes, setNotes] = useState<string[]>(() => { const saved = localStorage.getItem('notes'); return saved ? (JSON.parse(saved) as string[]) : []; });…How do you structure component state well: what should and should not be stored in it?
How do
preventDefault,stopPropagationand capture handlers work in React, and where does React attach its event listeners?type CardProps = { onOpen: () => void; onShare: () => void }; function Card({ onOpen, onShare }: CardProps) { return ( <div onClick={onOpen} onClickCapture={() => console.log('capture: runs first')}> <a…How do you handle high-frequency events such as
scroll,resizeorpointermovewithout re-rendering on every event?function ArticleHeader() { const barRef = useRef<HTMLDivElement>(null); const [scrolled, setScrolled] = useState(false); useEffect(() => { let frame = 0;…How would you implement undo and redo for a piece of React state?
type History<T> = { past: T[]; present: T; future: T[] };type HistoryAction<T> = { type: 'set'; value: T } | { type: 'undo' } | { type: 'redo' }; const LIMIT = 100; // keep memory bounded function historyReducer<T>(state: History<T>, action: HistoryAction<T>): History<T> {…