DEV Community

Cover image for 🔥 30 Days of Frontend - Day 1
Alaa Samy
Alaa Samy

Posted on

🔥 30 Days of Frontend - Day 1

What Actually Happens When State Changes in React?

When state changes, many developers think:

setState() → React updates the DOM
Enter fullscreen mode Exit fullscreen mode

That's a useful simplified model, but there's more happening in between.

A better mental model is:

State / Props change
        ↓
React schedules a render
        ↓
Component runs again
        ↓
React reconciles the new tree
        ↓
React commits the required DOM changes
Enter fullscreen mode Exit fullscreen mode

1. State or props change

For example:

const [count, setCount] = useState(0);

setCount(count + 1);
Enter fullscreen mode Exit fullscreen mode

The state update tells React that the component needs to be rendered again.

2. The component runs again

React calls the component function again using the new state:

function Counter() {
  const [count, setCount] = useState(0);

  return <button>{count}</button>;
}
Enter fullscreen mode Exit fullscreen mode

This is what we commonly call a re-render.

3. React creates the new element tree

The component produces a new React element tree based on the current state and props.

React now has:

Previous tree
      ↓
New tree
Enter fullscreen mode Exit fullscreen mode

It needs to determine what actually changed.

4. React reconciles the trees

React compares the new result with the previous one.

For example:

Before: <button>0</button>
After:  <button>1</button>
Enter fullscreen mode Exit fullscreen mode

React doesn't need to recreate the entire DOM.

It determines the necessary update.

5. React commits the changes

After React determines what needs to change, it commits those changes to the actual DOM.

So remember:

A re-render does NOT mean the entire DOM is recreated.

This distinction is important when thinking about React performance.

A component rendering again isn't automatically a performance problem.

Instead, ask:

Did this render produce unnecessary work?

That's where tools such as React DevTools Profiler become useful. They can help you identify expensive or unnecessary rendering before you start adding optimizations.

The mental model

Keep this simple flow in mind:

Update
  ↓
Render
  ↓
Reconcile
  ↓
Commit
Enter fullscreen mode Exit fullscreen mode

Understanding this flow makes React performance optimization much easier to reason about.

Before reaching for useMemo, useCallback, or React.memo, understand what is actually causing the work.

Profile first. Optimize second.

Top comments (0)