preact-custom-element
preact-custom-element copied to clipboard
Batch attributeChangedCallback / Safeguard required props
The setup:
- A small preact-application wrapped in preact-custom-element, accepting three props which all are required by the preact-application.
- The resulting custom element is dynamically created and updated inside a React-application
From my observations it does not seem like the wrapped preact-application is guaranteed to receive all props, with their corresponding values, in one pass. Even though they are provided to the custom element in "one go". I assume this has to do with how web components and the attributeChangedCallback work https://github.com/preactjs/preact-custom-element/blob/master/src/index.js#L28. Missing values for required props can of course be mitigated by having safeguards in place in the preact-application. But I want to discuss approches to include this functionality in this library instead
Thoughts/Questions:
- Would it be viable to extend the library with some sort of batch-functionality in https://github.com/preactjs/preact-custom-element/blob/master/src/index.js#L28 that can guarantee that provided props are passed along in an atomic way?
- Or could a strategy be to extend the register call, https://github.com/preactjs/preact-custom-element/blob/master/src/index.js#L3, to accept a propNames config that expresses required props and use these rules in https://github.com/preactjs/preact-custom-element/blob/master/src/index.js#L28 to determine whether the preact-application is ready to render or not?
To me, batching sounds like the proper solution for this issue 👍
Because connectedCallback
is called as soon as one property is set, the component will be rendered before all required props have a value. This appears to be fixed by simply removing the call to connectedCallback
from the property setters - it will be invoked by the browser anyways, seemingly after all properties have had a chance to be set. Some extra null-checking will be required here and there. What do you think?
Somewhat related, rerendering for every change could be bad for performance if many changes are made at once, and batching (even just deferring for 0 ms) could alleviate that. But maybe preact already does something about this?
@raihle Preact batches calls to setState
, but not render()/hydrate()
. So having batching in this adapter would be a welcome improvement as you outlined 👍
Is there any update one this issue? I'm currently running into the same situation.