Delayed React Rendering

Some of the plugins I’ve been working on rewriting lately to be fully block-based use React on the frontend for their interactive elements. When I first started moving from the shortcode-based elements with AJAX calls and manual DOM updating of pre-Gutenberg, I missed the quick initial page load of a page rendered in PHP. After many months and many false starts an idea came to me one night.

quick aside: the block I’m talking about here is essentially the core Latest Posts block with pagination added, not sure if that will help with visualization and understanding, but that is what I’m using as an example.

The official create-react-app and most of the tutorials that I’ve seen have a simple ReactDOM.render() that “controls the contents of the container node you pass in” located in the index.js file that is included in the HTML. My thought was why not move that render call (in my case wp.element.render) to an event listener? In this case there is a “Next” and “Previous” button that paginate the results, so I added an onclick listener to them that calls the render method.

So now the initial page is rendered in PHP and loaded as quickly as can be, but once the user click on the “Next” or “Previous” button, React takes over and re-renders the content using apiFetch.

The biggest downside to this approach was that I needed to write (and maintain) the “template” for the HTML in both PHP and JSX.

I’m sure there is more drawbacks or unforeseen consequences and I would love to hear them if you can think of any.





Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.