When React Renders
When React Renders
React renders in specific situations.
Initial Render
function App() {
return <h1>Hello, World!</h1>;
}
// First time component is mounted
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
Re-renders Happen When
- State changes
function Counter() {
const [count, setCount] = useState(0);
// Clicking button triggers re-render
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
- Props change
function Parent() {
const [name, setName] = useState("Alice");
// Changing name triggers re-render of Parent and Child
return (
<div>
<Child name={name} />
<button onClick={() => setName("Bob")}>Change Name</button>
</div>
);
}
function Child({ name }) {
return <p>{name}</p>;
}
- Parent re-renders
function Parent() {
const [count, setCount] = useState(0);
// Child re-renders even though its props don't change
return (
<div>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<Child /> // Re-renders with Parent
</div>
);
}
function Child() {
console.log("Child rendered");
return <p>I'm a child</p>;
}
- Context changes
const ThemeContext = createContext("light");
function App() {
const [theme, setTheme] = useState("light");
return (
<ThemeContext.Provider value={theme}>
<ThemedButton />
<button onClick={() => setTheme("dark")}>Toggle</button>
</ThemeContext.Provider>
);
}
function ThemedButton() {
const theme = useContext(ThemeContext);
// Re-renders when theme context changes
return <button className={theme}>Click</button>;
}
Reconciliation
Reconciliation
Reconciliation is React's algorithm for diffing Virtual DOM trees.
How It Works
- New Virtual DOM tree is created
- React compares new tree with previous tree
- React determines minimal changes
- Only changed parts are updated in real DOM
Diffing Algorithm
- Same element type: Update properties
- Different element type: Remove and re-create
- Keys help identify which items changed
// React sees same element type, updates properties
<div key="1" className="old" />
<div key="1" className="new" /> // Updates className
// React sees different element types, removes and re-creates
<div key="1" />
<span key="1" /> // Removes div, creates span
Keys in Lists
// Without keys: React re-renders all items
<ul>
<li>Alice</li>
<li>Bob</li>
</ul>
// With keys: React can identify changed items
<ul>
<li key="1">Alice</li>
<li key="2">Bob</li>
</ul>
Performance Implications
- Re-rendering doesn't mean re-mounting
- React only updates changed DOM nodes
- Keys help React optimize list updates
Batching Updates
Batching Updates
React batches state updates for performance.
What is Batching?
Multiple state updates in the same event handler are batched into a single re-render.
function Form() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [age, setAge] = useState(0);
const handleSubmit = () => {
// These three updates are batched into one re-render
setName("Alice");
setEmail("alice@example.com");
setAge(30);
};
}
Batching in React 18+
// React 18+ automatically batches all updates
function Component() {
const [count, setCount] = useState(0);
// Batched (single re-render)
const handleClick = () => {
setCount((c) => c + 1);
setCount((c) => c + 1);
setCount((c) => c + 1);
};
// Also batched in async code
const handleAsync = async () => {
await fetchData();
setCount((c) => c + 1); // Batched!
setName("Alice"); // Batched!
};
}
When Batching Doesn't Happen
// Native event handlers (outside React)
document.getElementById("btn").addEventListener("click", () => {
setCount((c) => c + 1); // Not batched in React 17
// React 18+ batches these too
});
// setTimeout
setTimeout(() => {
setCount((c) => c + 1); // Not batched in React 17
// React 18+ batches these too
}, 1000);
flushSync for Immediate Updates
import { flushSync } from "react-dom";
function handleClick() {
// Force immediate re-render
flushSync(() => {
setCount((c) => c + 1);
});
// DOM is updated here
flushSync(() => {
setName("Alice");
});
// DOM is updated here too
}
Functional Updates for Latest State
function Counter() {
const [count, setCount] = useState(0);
const incrementThree = () => {
// Without functional update: only adds 1
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
// With functional update: adds 3
setCount((prev) => prev + 1);
setCount((prev) => prev + 1);
setCount((prev) => prev + 1);
};
}
Practice Problems
Create a reusable React component implementing React Rendering. Include proper state management and accessibility.
Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where neededWrite unit and integration tests for React Rendering using React Testing Library.
Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility testsOptimize React Rendering for performance. Consider memoization, code splitting, and bundle size.
Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysisQuiz
1. When does React re-render?
2. What is reconciliation?
3. What is batching?
4. How do keys help with reconciliation?
Flashcards
Question
When does React render?
Click to reveal answer
Answer
On initial mount and when state, props, or context change
Question
What is reconciliation?
Click to reveal answer
Answer
React's algorithm for diffing Virtual DOM trees
Question
What is batching?
Click to reveal answer
Answer
Multiple state updates resulting in a single re-render
Question
How do keys help reconciliation?
Click to reveal answer
Answer
They help identify changed items in lists
Question
What is React Rendering?
Click to reveal answer
Answer
React Rendering is a key concept in frontend development.
Revision Notes
Key Takeaways
- 1.React renders on state, props, or context changes
- 2.Reconciliation diffs Virtual DOM efficiently
- 3.Batching combines updates into one re-render
- 4.Keys help React optimize list updates
- 5.React 18+ batches all updates automatically
Interview Tips
- •Explain when React re-renders
- •Describe the reconciliation process
- •Understand batching and functional updates
Cheat Sheet
Cheat Sheet
When React Renders
- Initial mount
- State changes
- Props change
- Parent re-renders
- Context changes
Reconciliation
- New Virtual DOM created
- Diff with previous tree
- Update minimal changes
Batching
// Multiple updates = one re-render
setName("Alice");
setEmail("alice@example.com");
setAge(30);
// Functional updates for latest state
setCount(prev => prev + 1);
Keys
// Help React identify changed items
{items.map(item => <li key={item.id}>{item.name}</li>)}