Sobes.tech
Middle+

What are reflow and repaint? What is forced reflow? How can rendering be optimized to reduce the number of forced reflows?

sobes.tech AI

Answer from AI

Reflow (or layout) is the process where the browser calculates the geometry of elements on the page: sizes, positions, hierarchy. This occurs when properties affecting size or position (e.g., width, height, fonts, margins) are changed.

Repaint is the process of redrawing elements on the screen when properties affecting appearance are changed, but not geometry (e.g., color, background, shadows).

Forced reflow is a situation where a script requests information about the current position or size of elements (e.g., via element.offsetWidth, getComputedStyle), which forces the browser to perform reflow immediately to return up-to-date data. This can significantly slow down rendering, especially if many such requests are made.

Rendering optimization:

  • Minimize changes that cause reflow by grouping style and class modifications.
  • Use requestAnimationFrame for deferred changes.
  • Avoid reading properties that trigger forced reflow immediately after DOM modifications.
  • Use CSS animations and transformations (transform, opacity) that do not cause reflow.
  • Cache values if you need to read sizes frequently.

Example:

// Bad: reading a property after style change triggers forced reflow
element.style.width = '100px';
console.log(element.offsetWidth); // forced reflow

// Better:
const width = element.offsetWidth; // read once
element.style.width = '100px';
// do not read immediately after change

Thus, reducing the number of forced reflows improves performance and interface smoothness.