← React Beginner Questions - Set 6 Q52
React Beginner Questions - Set 6
Two phases: render computes what should change, commit applies it. Everything you write happens in the first; only React touches the DOM in the second.
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
console.log('1. render phase', count); // may run more than once
function handleClick() {
setCount(c => c + 1); // batched
setCount(c => c + 1); // same tick: both apply, one render
console.log('2. handler finished, DOM not updated yet');
}
useEffect(() => {
console.log('3. commit done, DOM is up to date', count);
});
return <button onClick={handleClick}>{count}</button>;
}