React Battle Card
A concentrated cheat sheet for React interviews and daily development. Covers essential patterns, architectural decisions (Derived State), and the philosophy of 'Forced Simplicity'.
React Battle Card
🧠 The Philosophy: “Forced Simplicity”
- Do not over-engineer. If a simple
useStateworks, don’t useuseReducer - Declarative > Imperative. Describe what I want (
map), not how to get it (forloop) - Talk while I type. “I’m keeping this simple first…”
🛠️ Coding Patterns (Syntax)
1. Create Arrays (The “Clean” Way) Don’t use for loops. Use Array.from
1
2
// Good for Star Ratings, Pagination, Lists
const items = Array.from({ length: 5 }, (_, i) => i + 1);
2. Rendering Lists Always use .map() and always provide a unique key
1
2
3
{items.map((item) => (
<span key={item.id}>{item.name}</span>
))}
3. Controlled Inputs Never let an input manage itself. Bind value and onChange
1
2
3
4
<input
value={text}
onChange={(e) => setText(e.target.value)}
/>
4. Thread-Safe Updates When toggling or incrementing, use the Functional Update
1
2
// BAD: setValue(!value) -> Might be stale
// GOOD: setValue(prev => !prev) -> Always accurate
🏗️ Architecture & State
5. Derived State is King
- Rule: If I can calculate it, do not put it in state.
- The Trap: Storing
usersANDfilteredUsers. - The Fix: Store
users+search. CalculatefilteredUsersduring render. - Soundbite: “I’m using derived state here to avoid synchronization bugs.”
6. Dependency Arrays (useEffect, useMemo)
[]= Mount only (Run once).[prop]= Update (Run whenpropchanges).(missing)= Every Render (Danger ⚠️).
7. Performance Optimization Use useMemo for expensive derived state (like filtering a big list)
1
2
3
const filtered = useMemo(() => {
return list.filter(item => ...);
}, [list, filterTerm]);
🧪 Testing & Quality
8. Testing Hooks I cannot test hooks directly. Use the renderHook helper
1
2
3
4
5
6
7
8
import { renderHook, act } from "@testing-library/react";
// 1. Render
const { result } = renderHook(() => useToggle());
// 2. Act (Update State)
act(() => result.current.toggle());
// 3. Assert
expect(result.current.value).toBe(true);
9. Accessibility (The Senior Bonus)
- Add
role="button"to non-button clickables (like Stars). - Use
aria-label="Rate 5 stars"for screen readers.
🗣️ Quick Definitions (If asked “Why?”)
- Side Effect: “Any operation that reaches outside the component, like fetching data or changing the document title. We use
useEffectto keep the render pure.” - Hooks: “Functions that let functional components ‘hook into’ React features like state and lifecycle.”
This post is licensed under CC BY 4.0 by the author.
