In the react docs they give an example of css-in-js update, where useInsertionEffect ensures that the css updates are made before react starts updating/mutating the real dom.

It is mentioned that if styles are added while react is updating the dom, it will cause the browser to recalculate styles(build cssom) for every node in the react component tree.

Reference: https://github.com/reactwg/react-18/discussions/110#discussion-3619937

This effectively causes a recalculation of all CSS rules against all DOM nodes every frame while React is rendering. This is VERY slow.

Now my question is, if all we need is to append the style tag to the head before react starts updating the dom(executes render function), then why not just do that before react component returns, e.g. like the following:

function not_a_hook(rule) {
  if (!isInserted.has(rule)) {
      isInserted.add(rule);
      document.head.appendChild(getStyleForRule(rule));
    }
  return rule;
}

function Button() {
  const className = not_a_hook("<style> .myClass {width: 100px} </style>");
  return <div className={className} />;
}

Although I don't know what react expects for rule variable, in any case the function not_a_hook is gonna run before the Button function returns the renderable dom, react will be forced to append style tag, before starting the reconciliation, then why do we need the useInsertionEffect hook at all?

0

There are 0 best solutions below