React Basics
React How It Works
React keeps a lightweight JavaScript description of your UI in memory, compares the new description with the previous one after every state change, and then applies only the differences to the real DOM. This compare-then-patch cycle is called rendering and committing.
What is How It Works in React?
React keeps a lightweight JavaScript description of your UI in memory, compares the new description with the previous one after every state change, and then applies only the differences to the real DOM. This compare-then-patch cycle is called rendering and committing.
Why How It Works matters
Understanding the render cycle explains nearly every confusing React behaviour: why a component runs twice, why a state update does not appear immediately, why an effect fires again, and why unnecessary re-renders slow an app down.
How It Works example
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
console.log('render with count =', count);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}How this works
Every click calls setCount, which marks the component as needing an update. React then re-runs the Counter function from the top, producing fresh markup. It compares that output with the previous output and finds that only the button text changed, so it rewrites just that text node — the button element itself is never recreated.
Key points to remember
- Trigger: an initial mount or a state/props change schedules a render.
- Render: React calls your component function to get the new UI description. This must be pure — no DOM writes, no fetches.
- Commit: React applies the minimal DOM changes, then runs layout effects and effects.
- Rendering a component also re-renders its children unless they are memoised.
- Rendering is not the same as updating the DOM — React often renders and then changes nothing.
Common mistakes with How It Works
- Assuming the DOM is updated the moment setState is called — the update is scheduled, not immediate.
- Performing side effects (fetch, document.title, timers) directly in the component body instead of inside useEffect.
- Blaming "too many renders" for slowness before measuring — a render that produces no DOM change is usually cheap.
In development, React StrictMode deliberately calls your component function twice to surface impure code. Duplicate console logs in dev are expected and do not happen in production builds.
React How It Works— Interview Questions & FAQs
Why does my component render twice?+
In development, React StrictMode double-invokes component functions and effect setup to help you spot impure logic and missing cleanups. Production builds render once.
Does every state update repaint the whole page?+
No. React re-runs the component function and its children to build a new UI description, then updates only the DOM nodes whose attributes or text actually changed.
