โ๏ธReact Fundamentals
7.1Controlled vs Uncontrolled Components
A controlled component has its value driven by React state. A uncontrolled component keeps its value in the DOM, and you read it via a ref when needed.
| Aspect | Controlled | Uncontrolled |
|---|---|---|
| State owner | React (useState) | The DOM node itself |
| Value source | value prop | The DOM (accessed via ref) |
| Reading value | Always available in state | Read on demand via ref.current.value |
| Change handling | onChange updates state on every keystroke | No handler needed; read when you need it |
| Best for | Validation as you type, conditional UI, disabling submit, formatting input | Simple forms, file inputs, integrating non-React/3rd-party code |
// Controlled โ React is the single source of truth
function ControlledInput() {
const [name, setName] = useState('');
return <input value={name} onChange={(e) => setName(e.target.value)} />;
}
// Uncontrolled โ the DOM holds the value
function UncontrolledInput() {
const inputRef = useRef(null);
const handleSubmit = () => console.log(inputRef.current.value);
return (
<>
<input ref={inputRef} defaultValue="initial" />
<button onClick={handleSubmit}>Submit</button>
</>
);
}
Key nuances:
<input type="file">is always uncontrolled โ its value is read-only for security reasons; you can't set it from JS.- Use
defaultValue/defaultCheckedfor uncontrolled initial values, notvalue/checked. - A component switching from controlled to uncontrolled (value going from a defined string to
undefined) triggers a React warning. Keep it one or the other for the component's lifetime. - Libraries like React Hook Form deliberately use uncontrolled inputs under the hood for performance โ fewer re-renders per keystroke.
Interviewers probe: "When would you pick uncontrolled?" โ answer: file inputs, integrating with non-React libraries, or perf-sensitive large forms where per-keystroke re-renders hurt.
7.2useEffect vs useLayoutEffect
Both run after render, but at different points relative to the browser's paint.
| Aspect | useEffect | useLayoutEffect |
|---|---|---|
| Timing | After the browser paints (asynchronous) | After DOM mutations, before paint (synchronous) |
| Blocks paint? | No | Yes โ can delay visual update |
| Typical use | Data fetching, subscriptions, logging, timers, most side effects | Measuring DOM (size/position), synchronously re-positioning to avoid flicker |
| Risk | None to layout timing | Overuse blocks rendering, hurts perf |
| SSR | Runs only on client | Warns in SSR (no DOM on server) โ use useEffect or guard it |
// useLayoutEffect: measure then adjust BEFORE the user sees a flicker
function Tooltip({ targetRef }) {
const tooltipRef = useRef(null);
const [position, setPosition] = useState({ top: 0, left: 0 });
useLayoutEffect(() => {
const rect = targetRef.current.getBoundingClientRect();
setPosition({ top: rect.bottom, left: rect.left });
// This runs before paint, so the user never sees the tooltip in the wrong spot
}, [targetRef]);
return <div ref={tooltipRef} style={{ position: 'absolute', ...position }} />;
}
Rule of thumb: default to useEffect. Reach for useLayoutEffect only when you read layout and then mutate it, and a visible flicker would otherwise occur (tooltips, popovers, measuring text, scroll restoration).
7.3The Virtual DOM โ How It Actually Works
The Virtual DOM (VDOM) is a lightweight in-memory JavaScript representation of the real DOM. It's a tree of plain objects describing what the UI should look like.
The lifecycle:
- JSX โ elements. JSX compiles to
React.createElement()calls, which produce plain objects ({ type, props, children }). That tree is the virtual DOM. - State/prop change โ new tree. When state changes, React builds a new virtual tree for the affected subtree.
- Diffing (reconciliation). React compares the new tree against the previous one to find the minimal set of changes. (Details in 1.4.)
- Batching. Multiple state updates in the same event are collected and processed together.
- Commit. Only the actual differences are written to the real DOM, in one coordinated pass.
The important mental correction: the virtual DOM isn't "fast" because it's virtual. Manipulating a JS object tree isn't inherently faster than the DOM. The win is that React minimizes and batches real DOM writes โ the expensive operations (layout, paint) happen once for the smallest necessary change set, instead of many times as you'd get with naive imperative updates.
What it buys you: a declarative model. You describe what the UI should be for a given state, and React figures out how to get the DOM there. You never write manual DOM patching.
7.4Reconciliation (the Diffing Algorithm)
A naive tree-diff is O(nยณ). React makes it ~O(n) using two heuristics:
Heuristic 1 โ Different element types produce different trees.
- If an element's
typechanges (<div>โ<span>, orComponentAโComponentB), React tears down the old subtree entirely and builds the new one from scratch. State in the old subtree is lost. - If the
typeis the same, React keeps the DOM node and only updates changed attributes/props, then recurses into children.
Heuristic 2 โ Keys identify elements across renders in lists.
- Without keys, React matches list children by position (index). Inserting an item at the top shifts everything, causing React to think every item changed โ wasteful re-renders and potential state bugs.
- With stable, unique keys, React matches by identity. It knows which items moved, were added, or removed, and does the minimal work.
// Bad: no key (or index as key with a reorderable list)
{items.map((item) => <Row data={item} />)}
{items.map((item, i) => <Row key={i} data={item} />)} // breaks on reorder/insert
// Good: stable identity
{items.map((item) => <Row key={item.id} data={item} />)}
Why index-as-key is dangerous: if the list can reorder, filter, or have items inserted/removed anywhere but the end, index keys make React associate the wrong DOM node (and component state) with the wrong data. Symptoms: input values "jumping" to the wrong row, checkboxes checking the wrong item.
How this ties to performance: because same-type elements are reused and children with matching keys are reused, correct keys + React.memo let React skip re-rendering unchanged subtrees. This is the foundation everything in Part 3 builds on.
Modern note: the architecture above is the classic "stack" reconciler mental model. Since React 16, the actual engine is the Fiber reconciler, which additionally makes rendering interruptible โ React can pause, prioritize, and resume work. That's what powers concurrent features like
useTransitionanduseDeferredValue(Part 3). The diffing heuristics are the same; Fiber changed how the work is scheduled.
7.5Memory Leaks in React โ Causes & Fixes
A memory leak = memory that's no longer needed but can't be garbage-collected because something still references it. In React, this almost always means a side effect that outlives its component.
The four common causes and their fixes โ all solved by cleanup functions:
// 1. Timers not cleared
useEffect(() => {
const id = setInterval(poll, 1000);
return () => clearInterval(id); // โ fix
}, []);
// 2. Event listeners not removed
useEffect(() => {
const onResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', onResize);
return () => window.removeEventListener('resize', onResize); // โ fix
}, []);
// 3. Subscriptions not unsubscribed
useEffect(() => {
const sub = source.subscribe(handleData);
return () => sub.unsubscribe(); // โ fix
}, []);
// 4. State update after unmount (async resolves late)
useEffect(() => {
let active = true;
fetchData().then((data) => {
if (active) setData(data); // โ guard prevents update on unmounted component
});
return () => { active = false; };
}, []);
Other, subtler sources:
- Stale closures capturing large objects. A callback that closes over a big array keeps it alive as long as the callback lives.
- Detached DOM nodes held in a ref after removal.
- Global caches / module-level Maps that grow forever and are never pruned.
AbortControllerfor fetch โ the modern way to cancel in-flight requests on unmount:
useEffect(() => {
const controller = new AbortController();
fetch(url, { signal: controller.signal })
.then((r) => r.json())
.then(setData)
.catch((err) => { if (err.name !== 'AbortError') throw err; });
return () => controller.abort();
}, [url]);
How to detect: Chrome DevTools โ Memory tab โ take heap snapshots before/after mounting-unmounting a component repeatedly. Growing detached nodes or listener counts signal a leak. The Performance monitor's "JS heap size" climbing steadily under normal use is another tell.
๐ง Quiz: React Fundamentals
5 questions1Which input type is ALWAYS uncontrolled in React?
2You need to measure a DOM node and reposition it before the user sees a flicker. Which hook fits?
3Why is using the array index as a key dangerous for a reorderable list?
4What is the real reason the Virtual DOM helps performance?
5A common cause of memory leaks in React is: