Skip to main content

Why is a patch flag needed?

Patch Flag is a special flag that Vue 3 adds to every virtual node when compiling a template. These flags help the render engine understand exactly which parts of the node can change, so it does not need to run a full diff.

In simpler terms:

A Patch Flag is a hint for the engine about what needs to be updated and what can be skipped. This lets Vue update the DOM in a targeted way instead of comparing the entire node.


Why is a patch flag needed? (the main reason)

To greatly speed up the Virtual DOM.

In a classic Virtual DOM (for example, React without optimizations):

  1. ALL props are compared
  2. ALL attributes are compared
  3. ALL child nodes are compared

Vue 3 does it differently:

  • at compile time it figures out which parts of the template are dynamic

  • it marks such nodes with a special flag

  • at runtime it does not check the whole tree, it applies only the update that's needed

  • this is a huge performance gain.


How does a patch flag work?

Example:

vue
<p>{{ message }}</p>

Vue understands that only the text is dynamic, and generates the node:

js
createVNode("p", null, message, PatchFlags.TEXT)

On update, Vue knows:

  • it does NOT need to compare props
  • it does NOT need to compare attributes
  • it does NOT need to compare children (except the text)
  • it only needs to update the text node

Examples of patch flags

Here are a few key flags worth knowing:

FlagDescription
TEXTOnly the text changes
PROPSOnly specific props change
CLASSOnly the class changes
STYLEOnly the styles change
FULL_PROPSAll props are dynamic
HYDRATE_EVENTSEvents are attached dynamically
KEYED_FRAGMENTA fragment with a keyed list
UNKEYED_FRAGMENTA fragment with an unkeyed list

Vue uses exactly the update operations it needs, rather than trying to do "everything".


Why do patch flags speed up Vue?

1. Vue does not run a full diff

Everything static is removed from the diff tree. Vue updates only what is marked with a flag.

2. Vue skips expensive checks

For example, if the flag is TEXT, neither props, nor events, nor attributes are checked.

3. Vue does not recreate unnecessary virtual nodes

If an element is static, it is created once.

4. The more flags, the faster the SPA

Because Vue spends less time on comparisons.


An example to understand this

Template:

vue
<button @click="inc" :class="active ? 'on' : 'off'"> {{ count }} </button>

Vue will mark:

  • the text → TEXT
  • class → CLASS
  • the event → HYDRATE_EVENTS

When count updates:

  • only the text updates
  • class and the event are NOT checked

When active changes:

  • only the class updates
  • the text and the event are NOT checked

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.