Remove/restrict wp-init effect to encourage/enforce initial state to be supplied by PHP for SSR #52889
Replies: 1 comment 2 replies
-
Restricting APIs to avoid bad UX is an interesting topic, although in this case, I'm not sure if it's actually feasible. First, there are use cases where modifying the Second, even if you remove
So, shouldn't we address this anti-pattern with education rather than trying to restrict the API? The Interactivity API is designed to leverage the server, so that's what we should emphasize when we teach it: <?php
$is2024 = date( 'Y' ) >= 2024;
?>
<div
data-wp-interactive
data-wp-context='{ "{{namespace}}": { "isOpen": <?php echo $is2024; ?> } }'
data-wp-bind--hidden="!context.{{namespace}}.isOpen"
>
<p style="font-size: 1000px">Hello 2024!!!!</p>
</div> By the way, for reference, you can do the exact same thing in React, and it would also lead to the exact same bad UX: const Comp = () => {
const [isShown, setIsShown] = useState(false);
useEffect(() => {
setIsShown(new Date().getFullYear() >= 2024);
}, []);
return (
<div hidden={!isShown}>
<p style="font-size: 1000px">Hello 2024!!!!</p>
</div>
);
}; Let me know what you think 🙂 |
Beta Was this translation helpful? Give feedback.
-
To circle back on my comment on Proposal: The Interactivity API – A better developer experience in building interactive blocks:
To this @luisherranz replied:
I wanted to elaborate a bit more on the concern about the client-side
init
code mutating the state which causes some DOM update: in other words, for there to be a possibility that the initial state may not be SSR'ed. The lack of SSR endangers both CLS and INP.Let's say that you have some element that should conditionally display after some date:
And your JS code contains:
This would result in the element being hidden after the DOM has loaded, resulting in layout shift.
Instead, I think we should encourage as much as possible that such an initial state should be supplied by PHP. One way to achieve this would be to eliminate the
wp-init
effect entirely, or to make the suppliedcontext
read-only for this effect.Beta Was this translation helpful? Give feedback.
All reactions