---
title: Building Gutenberg Blocks with React and Block API v3
description: Build modern Gutenberg blocks with Block API v3, React editor state, InspectorControls, core-data and secure dynamic server-side rendering.
url: https://moxseo.com/blogs/building-gutenberg-blocks-react-block-api-v3
date_modified: 2026-10-28
author: Aditya Bhimrajka
language: en_US
---

## Key takeaways

- Block API v3 moves block setup into a declarative `block.json` schema, with automatic asset registration and leaner client-side hydration, which keeps block-heavy pages lighter for visitors and for Core Web Vitals.
- Rendering through `render.php` ends the “Block validation failed” editor errors that appear when you change a block’s markup on a site with thousands of published posts.
- When React inspector controls read WordPress REST entities, use `@wordpress/core-data` selectors such as `useEntityRecords` so results are cached in memory and shared instead of fetched repeatedly.
- Calling `fetch()` or `apiFetch()` straight from a render loop, without caching, sets off endless re-render and request cascades that max out the browser’s CPU.
- Limiting `InnerBlocks` with a strict `allowedBlocks` array and a locked template stops content authors from breaking the layout rules of a design system.
- Jest and React Testing Library suites, paired with PHPUnit tests of the server-rendered output, catch attribute regressions before a plugin update ships.

Gutenberg stopped being a plain rich-text editor a while ago; it is now a layout and component framework in its own right. With **Block API v3** stable, writing blocks properly means applying the usual engineering habits: typed attribute schemas, isolated state, asynchronous REST entity binding, declarative inspector sidebars and predictable server-side rendering.

Teams coming from classic PHP shortcodes or legacy ACF blocks tend to hit the same traps. React hook dependency arrays set up wrongly produce endless REST fetch loops. Fragile static `save()` markup triggers block validation errors across thousands of published posts. PHP renderers that skip escaping open the door to Cross-Site Scripting (XSS).

This guide walks through how Block API v3 works, weighs static against dynamic rendering, builds a React inspector control on `@wordpress/core-data`, writes a safe PHP renderer with transient caching, sets up nested `InnerBlocks` templates, and finishes with Jest and PHPUnit test suites.

## How Block API v3 Works: the `block.json` Schema

Blocks are now declared in `block.json`. Setting `apiVersion: 3` turns on iframe-isolated editor rendering and ES module resolution, and it prepares the block for the WordPress Interactivity API.

Below is the `block.json` we use for a dynamic **Enterprise Product Showcase Block**:

```
{
  "$schema": "https://schemas.wp.org/trunk/block.json",
  "apiVersion": 3,
  "name": "wpstack/product-showcase",
  "version": "2.4.0",
  "title": "WPStack Product Showcase",
  "category": "widgets",
  "icon": "store",
  "description": "Dynamic, high-performance product showcase with live REST entity selection and transient caching.",
  "keywords": ["products", "woocommerce", "showcase", "wpstack"],
  "textdomain": "wpstack",
  "attributes": {
    "selectedCategory": {
      "type": "string",
      "default": "all"
    },
    "postsPerPage": {
      "type": "number",
      "default": 6
    },
    "columns": {
      "type": "number",
      "default": 3
    },
    "showPrice": {
      "type": "boolean",
      "default": true
    },
    "showRating": {
      "type": "boolean",
      "default": true
    },
    "orderBy": {
      "type": "string",
      "default": "date"
    },
    "order": {
      "type": "string",
      "default": "desc"
    }
  },
  "supports": {
    "align": ["wide", "full"],
    "html": false,
    "customClassName": true,
    "spacing": {
      "margin": true,
      "padding": true
    },
    "color": {
      "background": true,
      "text": true
    }
  },
  "editorScript": "file:./build/index.js",
  "editorStyle": "file:./build/index.css",
  "style": "file:./build/style-index.css",
  "render": "file:./render.php"
}
```

## Choosing Between Static `save()` and Dynamic `render.php`

The first big design choice for a custom block is how it renders:

| Feature / Dimension | Static Block (`save.js`) | Dynamic Block (`render.php`) |
| --- | --- | --- |
| **Markup Storage** | Rendered HTML saved directly into `post_content` in MySQL | Only JSON attributes saved in block delimiter comment |
| **Template Mutation Risk** | **High** (Modifying HTML structure breaks existing posts) | **Zero** (Markup changes propagate instantly to all posts) |
| **Dynamic Data Handling** | Cannot query live data (prices, stock, recent posts) | Executes live PHP queries on every uncached page load |
| **Page Cache Performance** | Zero PHP execution overhead on static cached pages | Requires object caching or edge caching for database queries |
| **Editing Complexity** | Requires synchronized `edit.js` and `save.js` structures | `save.js` simply returns `null`; PHP handles all output |
| **Recommended Use Case** | Static text callouts, hero banners, feature grids | Product lists, dynamic post queries, pricing calculators |

Anything driven by live data, such as listings, pricing tables or query-based components, **should use dynamic rendering through `render.php`**. Baking database records into static HTML leaves stale data in the content and causes block validation failures whenever the template changes.

## The React Editor Component (`edit.js`)

The editor component draws the canvas with `@wordpress/block-editor`, builds sidebar controls from `@wordpress/components`, and syncs REST entities asynchronously through `@wordpress/core-data`.

### 1. Avoiding Endless Re-Renders with Core Data

A classic beginner bug is calling `apiFetch()` inside `useEffect()` with no memoization, so the data is fetched again on every keystroke. `useEntityRecords()` from `@wordpress/core-data` avoids this: WordPress caches the HTTP response, deduplicates identical requests and keeps Redux state in step across every open editor component.

```
// src/edit.jsx
import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls } from '@wordpress/block-editor';
import {
    PanelBody,
    SelectControl,
    RangeControl,
    ToggleControl,
    Spinner,
    Placeholder,
} from '@wordpress/components';
import { useEntityRecords } from '@wordpress/core-data';
import ServerSideRender from '@wordpress/server-side-render';

export default function Edit({ attributes, setAttributes }) {
    const {
        selectedCategory,
        postsPerPage,
        columns,
        showPrice,
        showRating,
        orderBy,
        order,
    } = attributes;

    const blockProps = useBlockProps({
        className: `wpstack-product-showcase-grid columns-${columns}`,
    });

    // Asynchronously fetch WooCommerce product categories via Core Data
    const { records: categories, hasResolved: hasResolvedCategories } = useEntityRecords(
        'taxonomy',
        'product_cat',
        { per_page: 100, hide_empty: true }
    );

    // Format categories for SelectControl
    const categoryOptions = [
        { label: __('All Categories', 'wpstack'), value: 'all' },
        ...(categories || []).map((cat) => ({
            label: `${cat.name} (${cat.count})`,
            value: String(cat.id),
        })),
    ];

    return (
        <>
            <InspectorControls>
                <PanelBody title={__('Query Settings', 'wpstack')} initialOpen={true}>
                    {!hasResolvedCategories ? (
                        <Spinner />
                    ) : (
                        <SelectControl
                            label={__('Filter by Category', 'wpstack')}
                            value={selectedCategory}
                            options={categoryOptions}
                            onChange={(value) => setAttributes({ selectedCategory: value })}
                        />
                    )}

                    <RangeControl
                        label={__('Products per Page', 'wpstack')}
                        value={postsPerPage}
                        onChange={(value) => setAttributes({ postsPerPage: value })}
                        min={1}
                        max={24}
                    />

                    <SelectControl
                        label={__('Order By', 'wpstack')}
                        value={orderBy}
                        options={[
                            { label: __('Published Date', 'wpstack'), value: 'date' },
                            { label: __('Price', 'wpstack'), value: 'price' },
                            { label: __('Popularity / Sales', 'wpstack'), value: 'popularity' },
                            { label: __('Alphabetical Title', 'wpstack'), value: 'title' },
                        ]}
                        onChange={(value) => setAttributes({ orderBy: value })}
                    />

                    <SelectControl
                        label={__('Sort Order', 'wpstack')}
                        value={order}
                        options={[
                            { label: __('Descending (Z-A, Newest)', 'wpstack'), value: 'desc' },
                            { label: __('Ascending (A-Z, Oldest)', 'wpstack'), value: 'asc' },
                        ]}
                        onChange={(value) => setAttributes({ order: value })}
                    />
                </PanelBody>

                <PanelBody title={__('Layout & Display Controls', 'wpstack')} initialOpen={false}>
                    <RangeControl
                        label={__('Grid Columns', 'wpstack')}
                        value={columns}
                        onChange={(value) => setAttributes({ columns: value })}
                        min={1}
                        max={6}
                    />

                    <ToggleControl
                        label={__('Display Product Price', 'wpstack')}
                        checked={showPrice}
                        onChange={(value) => setAttributes({ showPrice: value })}
                    />

                    <ToggleControl
                        label={__('Display Customer Rating', 'wpstack')}
                        checked={showRating}
                        onChange={(value) => setAttributes({ showRating: value })}
                    />
                </PanelBody>
            </InspectorControls>

            <div {...blockProps}>
                <ServerSideRender
                    block="wpstack/product-showcase"
                    attributes={attributes}
                    LoadingResponsePlaceholder={() => (
                        <Placeholder icon="store" label={__('Loading Product Showcase Preview...', 'wpstack')}>
                            <Spinner />
                        </Placeholder>
                    )}
                />
            </div>
        </>
    );
}

```

## A Safe PHP Renderer (`render.php`)

With Block API v3, putting `"render": "file:./render.php"` in `block.json` makes WordPress run that PHP file whenever the block is output on the front end. It receives the attributes as `$attributes`, the inner content as `$content` and the block instance as `$block`.

To keep rendering under 5ms, `render.php` uses persistent Redis or transient caching, escapes output late with `esc_html()` and `esc_url()`, and falls back to WooCommerce templates where needed:

```
<?php

declare(strict_types=1);

/**
 * Dynamic Server-Side Renderer for WPStack Product Showcase Block.
 *
 * @var array<string, mixed> $attributes Block attributes defined in block.json.
 * @var string               $content    Block inner content.
 * @var WP_Block             $block      Block instance.
 */

if (!defined('ABSPATH')) {
    exit;
}

// 1. Sanitize & Normalize Attributes
$category_id   = sanitize_text_field($attributes['selectedCategory'] ?? 'all');
$posts_per_page = min(24, max(1, (int) ($attributes['postsPerPage'] ?? 6)));
$columns        = min(6, max(1, (int) ($attributes['columns'] ?? 3)));
$show_price     = (bool) ($attributes['showPrice'] ?? true);
$show_rating    = (bool) ($attributes['showRating'] ?? true);
$order_by       = sanitize_key($attributes['orderBy'] ?? 'date');
$order          = strtolower((string) ($attributes['order'] ?? 'desc')) === 'asc' ? 'ASC' : 'DESC';

// 2. Build Cache Key
$cache_key = sprintf(
    'wpstack_showcase_%s_%d_%d_%s_%s_%d_%d',
    md5($category_id),
    $posts_per_page,
    $columns,
    $order_by,
    $order,
    $show_price ? 1 : 0,
    $show_rating ? 1 : 0
);

$cached_html = wp_cache_get($cache_key, 'wpstack_blocks');
if (is_string($cached_html) && !empty($cached_html) && !is_user_logged_in()) {
    echo $cached_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    return;
}

// 3. Construct Query Arguments
$query_args = [
    'post_type'      => 'product',
    'post_status'    => 'publish',
    'posts_per_page' => $posts_per_page,
    'order'          => $order,
    'no_found_rows'  => true, // Performance optimization: bypass SQL_CALC_FOUND_ROWS
];

switch ($order_by) {
    case 'price':
        $query_args['meta_key'] = '_price';
        $query_args['orderby']  = 'meta_value_num';
        break;
    case 'popularity':
        $query_args['meta_key'] = 'total_sales';
        $query_args['orderby']  = 'meta_value_num';
        break;
    case 'title':
        $query_args['orderby'] = 'title';
        break;
    default:
        $query_args['orderby'] = 'date';
        break;
}

if ($category_id !== 'all' && is_numeric($category_id)) {
    $query_args['tax_query'] = [
        [
            'taxonomy' => 'product_cat',
            'field'    => 'term_id',
            'terms'    => (int) $category_id,
        ],
    ];
}

$products_query = new WP_Query($query_args);

// Extract block wrapper attributes (supports colors, margins, classes)
$wrapper_attributes = get_block_wrapper_attributes([
    'class' => sprintf('wpstack-product-grid columns-%d', $columns),
]);

ob_start();
?>

<div <?php echo $wrapper_attributes; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
    <?php if ($products_query->have_posts()) : ?>
        <ul class="wpstack-product-list">
            <?php
            while ($products_query->have_posts()) :
                $products_query->the_post();
                $product = function_exists('wc_get_product') ? wc_get_product(get_the_ID()) : null;
                if (!$product) {
                    continue;
                }
                ?>
                <li class="wpstack-product-card">
                    <a href="<?php echo esc_url($product->get_permalink()); ?>" class="wpstack-product-link">
                        <div class="wpstack-product-thumbnail">
                            <?php echo $product->get_image('woocommerce_thumbnail'); // phpcs:ignore ?>
                        </div>
                        <h3 class="wpstack-product-title"><?php echo esc_html($product->get_name()); ?></h3>
                    </a>

                    <?php if ($show_rating && function_exists('wc_get_rating_html')) : ?>
                        <div class="wpstack-product-rating">
                            <?php echo wc_get_rating_html($product->get_average_rating()); // phpcs:ignore ?>
                        </div>
                    <?php endif; ?>

                    <?php if ($show_price) : ?>
                        <div class="wpstack-product-price">
                            <?php echo $product->get_price_html(); // phpcs:ignore ?>
                        </div>
                    <?php endif; ?>

                    <div class="wpstack-product-cta">
                        <a href="<?php echo esc_url($product->add_to_cart_url()); ?>" class="button wpstack-btn-add">
                            <?php echo esc_html($product->add_to_cart_text()); ?>
                        </a>
                    </div>
                </li>
            <?php endwhile; ?>
        </ul>
        <?php wp_reset_postdata(); ?>
    <?php else : ?>
        <p class="wpstack-no-products"><?php esc_html_e('No products found matching the criteria.', 'wpstack'); ?></p>
    <?php endif; ?>
</div>

<?php
$output = ob_get_clean();

// Store in persistent object cache for 1 hour
if (!is_user_logged_in()) {
    wp_cache_set($cache_key, $output, 'wpstack_blocks', HOUR_IN_SECONDS);
}

echo $output; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

```

## A Custom REST Autocomplete Endpoint

On a site with 10,000+ products, loading every category or item into a plain dropdown will freeze the browser. A purpose-built REST autocomplete endpoint backed by MySQL `FULLTEXT` search solves that:

```
<?php

declare(strict_types=1);

namespace WPStack\Blocks;

use WP_REST_Controller;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

final class ProductSearchRestController extends WP_REST_Controller {
    public const NAMESPACE = 'wpstack/v1';
    public const REST_BASE = 'products-autocomplete';

    public function register_routes(): void {
        register_rest_route(
            self::NAMESPACE,
            '/' . self::REST_BASE,
            [
                [
                    'methods'             => WP_REST_Server::READABLE,
                    'callback'            => [$this, 'search_products'],
                    'permission_callback' => [$this, 'check_read_permissions'],
                    'args'                => [
                        'search' => [
                            'required'          => true,
                            'type'              => 'string',
                            'sanitize_callback' => 'sanitize_text_field',
                        ],
                    ],
                ],
            ]
        );
    }

    public function check_read_permissions(): bool {
        return current_user_can('edit_posts');
    }

    public function search_products(WP_REST_Request $request): WP_REST_Response {
        global $wpdb;
        $term = (string) $request->get_param('search');

        if (strlen($term) < 2) {
            return new WP_REST_Response([], 200);
        }

        $like = '%' . $wpdb->esc_like($term) . '%';
        $sql  = "SELECT ID, post_title 
                 FROM {$wpdb->posts} 
                 WHERE post_type = 'product' 
                   AND post_status = 'publish' 
                   AND post_title LIKE %s 
                 ORDER BY post_title ASC 
                 LIMIT 15";

        $results = $wpdb->get_results($wpdb->prepare($sql, $like), ARRAY_A);

        $formatted = [];
        foreach ($results as $row) {
            $formatted[] = [
                'id'    => (int) $row['ID'],
                'title' => (string) $row['post_title'],
            ];
        }

        return new WP_REST_Response($formatted, 200);
    }
}

```

## Adding Front-End Behavior with the Interactivity API

Adding interactivity to blocks (instant category filters, live search, tab switching) used to mean shipping a heavy standalone React app to the front end or writing fragile vanilla JavaScript listeners.

The **WordPress Interactivity API** (stable since WordPress 6.5 and extended in 6.6) replaces that with declarative HTML directives. All blocks on a page share one small runtime (about 10 KB), which keeps Interaction to Next Paint (INP) under 50ms.

### 1. Directives in `render.php`

Next we add the interactive directives to the `render.php` template:

```
<?php
// Extracted snippet from render.php demonstrating Interactivity API directives
$initial_context = [
    'activeFilter' => $category_id,
    'isLoading'    => false,
    'quickViewOpen' => false,
    'selectedProduct' => null,
];
?>

<div 
    <?php echo $wrapper_attributes; // phpcs:ignore ?>
    data-wp-interactive="wpstack/product-showcase"
    data-wp-context='<?php echo esc_attr(wp_json_encode($initial_context)); ?>'
>
    <!-- Interactive Category Filter Bar -->
    <div class="wpstack-filter-bar">
        <button 
            type="button" 
            class="wpstack-filter-btn"
            data-wp-on--click="actions.setFilter"
            data-wp-class--active="callbacks.isAllActive"
            data-category="all"
        >
            <?php esc_html_e('All Items', 'wpstack'); ?>
        </button>
        <button 
            type="button" 
            class="wpstack-filter-btn"
            data-wp-on--click="actions.setFilter"
            data-wp-class--active="callbacks.isCategoryActive"
            data-category="featured"
        >
            <?php esc_html_e('Featured Collection', 'wpstack'); ?>
        </button>
    </div>

    <!-- Live Loading Spinner -->
    <div class="wpstack-loading-overlay" data-wp-bind--hidden="!context.isLoading">
        <span class="spinner"></span>
    </div>

    <!-- Product Grid Container -->
    <ul class="wpstack-product-list" data-wp-watch="callbacks.logStateChange">
        <!-- Rendered product items -->
    </ul>
</div>

```

### 2. The Store Module (`view.js`)

The reactive store lives in `src/view.js`. It responds to user actions, updates context state and drives client-side navigation:

```
// src/view.js
import { store, getContext, getElement } from '@wordpress/interactivity';

store('wpstack/product-showcase', {
    state: {
        get currentCategory() {
            const context = getContext();
            return context.activeFilter;
        },
    },
    actions: {
        setFilter(event) {
            const context = getContext();
            const { ref } = getElement();
            const newCategory = ref.getAttribute('data-category');

            if (context.activeFilter === newCategory) {
                return;
            }

            context.activeFilter = newCategory;
            context.isLoading = true;

            // Fetch filtered HTML snippet via WordPress REST API or Interactivity Router
            fetch(`/wp-json/wpstack/v1/products/partial?category=${newCategory}`)
                .then((res) => res.json())
                .then((data) => {
                    if (data.html) {
                        const list = ref.closest('[data-wp-interactive]').querySelector('.wpstack-product-list');
                        if (list) {
                            list.innerHTML = data.html;
                        }
                    }
                })
                .catch((err) => console.error('Filter fetch failed', err))
                .finally(() => {
                    context.isLoading = false;
                });
        },
        toggleQuickView(productId) {
            const context = getContext();
            context.quickViewOpen = !context.quickViewOpen;
            context.selectedProduct = productId;
        },
    },
    callbacks: {
        isAllActive() {
            const context = getContext();
            return context.activeFilter === 'all';
        },
        isCategoryActive() {
            const context = getContext();
            const { ref } = getElement();
            return context.activeFilter === ref.getAttribute('data-category');
        },
        logStateChange() {
            const context = getContext();
            console.debug('WPStack Showcase State Updated:', context);
        },
    },
});

```

## Composing with InnerBlocks and Passing Context

Complex components, such as multi-column pricing tables, tabbed card containers or testimonial sliders, work best as nested blocks. Gutenberg supports that with `<InnerBlocks />` plus `providesContext` and `usesContext`.

### 1. Parent and Child `block.json` Files

```
// parent-block.json
{
  "name": "wpstack/pricing-table",
  "title": "Pricing Table Container",
  "providesContext": {
    "wpstack/currency": "currencySymbol",
    "wpstack/billingPeriod": "billingPeriod"
  },
  "attributes": {
    "currencySymbol": { "type": "string", "default": "$" },
    "billingPeriod": { "type": "string", "default": "monthly" }
  }
}

// child-block.json
{
  "name": "wpstack/pricing-tier-card",
  "title": "Pricing Tier Card",
  "parent": ["wpstack/pricing-table"],
  "usesContext": ["wpstack/currency", "wpstack/billingPeriod"],
  "attributes": {
    "tierTitle": { "type": "string", "default": "Pro Plan" },
    "monthlyPrice": { "type": "number", "default": 49 }
  }
}
```

### 2. A Parent Edit Component with a Locked Template

```
// src/pricing-table/edit.jsx
import { useBlockProps, InnerBlocks, InspectorControls } from '@wordpress/block-editor';
import { PanelBody, SelectControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';

const ALLOWED_BLOCKS = ['wpstack/pricing-tier-card'];
const TEMPLATE = [
    ['wpstack/pricing-tier-card', { tierTitle: 'Starter Plan', monthlyPrice: 19 }],
    ['wpstack/pricing-tier-card', { tierTitle: 'Professional Plan', monthlyPrice: 49 }],
    ['wpstack/pricing-tier-card', { tierTitle: 'Enterprise Plan', monthlyPrice: 99 }],
];

export default function PricingTableEdit({ attributes, setAttributes }) {
    const { currencySymbol, billingPeriod } = attributes;
    const blockProps = useBlockProps({ className: 'wpstack-pricing-table-container' });

    return (
        <>
            <InspectorControls>
                <PanelBody title={__('Global Pricing Settings', 'wpstack')}>
                    <SelectControl
                        label={__('Currency Symbol', 'wpstack')}
                        value={currencySymbol}
                        options={[
                            { label: 'USD ($)', value: '$' },
                            { label: 'EUR (€)', value: '€' },
                            { label: 'GBP (£)', value: '£' },
                        ]}
                        onChange={(val) => setAttributes({ currencySymbol: val })}
                    />
                    <SelectControl
                        label={__('Billing Interval', 'wpstack')}
                        value={billingPeriod}
                        options={[
                            { label: __('Monthly Billing', 'wpstack'), value: 'monthly' },
                            { label: __('Annual Billing (20% Discount)', 'wpstack'), value: 'annual' },
                        ]}
                        onChange={(val) => setAttributes({ billingPeriod: val })}
                    />
                </PanelBody>
            </InspectorControls>

            <div {...blockProps}>
                <InnerBlocks
                    allowedBlocks={ALLOWED_BLOCKS}
                    template={TEMPLATE}
                    templateLock="all"
                    orientation="horizontal"
                />
            </div>
        </>
    );
}

```

## Block Transforms: Moving Legacy Shortcodes to Blocks

Moving a large site from legacy shortcodes (for example `[wpstack_showcase category="shoes" limit="6"]`) to blocks should not mean editors rebuild hundreds of pages by hand. A `transforms` definition in `src/transforms.js` converts them automatically:

```
// src/transforms.js
import { createBlock } from '@wordpress/blocks';

const transforms = {
    from: [
        {
            type: 'shortcode',
            tag: 'wpstack_showcase',
            attributes: {
                selectedCategory: {
                    type: 'string',
                    shortcode: (attrs) => attrs.named.category || 'all',
                },
                postsPerPage: {
                    type: 'number',
                    shortcode: (attrs) => (attrs.named.limit ? parseInt(attrs.named.limit, 10) : 6),
                },
                columns: {
                    type: 'number',
                    shortcode: (attrs) => (attrs.named.cols ? parseInt(attrs.named.cols, 10) : 3),
                },
                showPrice: {
                    type: 'boolean',
                    shortcode: (attrs) => attrs.named.hide_price !== 'true',
                },
            },
            transform: (attributes) => {
                return createBlock('wpstack/product-showcase', attributes);
            },
        },
        {
            type: 'block',
            blocks: ['core/query'],
            transform: (attributes) => {
                return createBlock('wpstack/product-showcase', {
                    postsPerPage: attributes.query?.perPage || 6,
                    selectedCategory: 'all',
                });
            },
        },
    ],
};

export default transforms;

```

## Webpack Build Pipeline and Bundle Size

Custom block bundles should not ship their own copies of WordPress core libraries (React, ReactDOM, Lodash, Moment.js), or Core Web Vitals suffer. The `@wordpress/dependency-extraction-webpack-plugin` rewrites imports such as `import React from 'react'` into references to the globals already on the page (`window.React` and `window.wp.*`):

```
// webpack.config.js
const defaultConfig = require('@wordpress/scripts/config/webpack.config');
const DependencyExtractionWebpackPlugin = require('@wordpress/dependency-extraction-webpack-plugin');
const path = require('path');

module.exports = {
    ...defaultConfig,
    entry: {
        index: path.resolve(__dirname, 'src/index.jsx'),
        view: path.resolve(__dirname, 'src/view.js'),
    },
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: '[name].js',
    },
    plugins: [
        ...defaultConfig.plugins.filter(
            (plugin) => plugin.constructor.name !== 'DependencyExtractionWebpackPlugin'
        ),
        new DependencyExtractionWebpackPlugin({
            injectPolyfill: false,
            combineAssets: true,
        }),
    ],
    optimization: {
        ...defaultConfig.optimization,
        usedExports: true, // Enable tree-shaking
    },
};

```

## Block Bindings API (WordPress 6.5+): Binding Meta Without a Custom Block

The **Block Bindings API** (added in WordPress 6.5 and extended in 6.6) is a significant change. Before it, tying a core paragraph, heading or image block to a custom meta field meant writing a custom block from scratch.

Now you can attach core block attributes to post meta keys declaratively in the block markup, with no React rendering code:

```
<!-- wp:paragraph {
    "metadata": {
        "bindings": {
            "content": {
                "source": "core/post-meta",
                "args": {
                    "key": "wpstack_product_sku"
                }
            }
        }
    }
} -->
<p>SKU Placeholder</p>
<!-- /wp:paragraph -->
```

You can also register your own binding sources in PHP to pull values from third-party APIs, weather feeds or user session state:

```
<?php

declare(strict_types=1);

namespace WPStack\Blocks;

final class CustomBlockBindings {
    public static function register(): void {
        add_action('init', static function (): void {
            if (!function_exists('register_block_bindings_source')) {
                return;
            }

            register_block_bindings_source(
                'wpstack/user-tier',
                [
                    'label'              => __('Current User Subscription Tier', 'wpstack'),
                    'get_value_callback' => static function (array $source_args): ?string {
                        if (!is_user_logged_in()) {
                            return __('Guest Visitor', 'wpstack');
                        }
                        $user_id = get_current_user_id();
                        $tier    = get_user_meta($user_id, 'wpstack_subscription_tier', true);
                        return is_string($tier) && !empty($tier) ? $tier : __('Free Member', 'wpstack');
                    },
                ]
            );
        });
    }
}

```

## Block Variations as Reusable Presets

Variations let a single block type appear in the inserter in several preconfigured forms (such as “Featured Product Showcase”, “Discounted Clearance Grid” or “Best Sellers List”) without registering separate block types:

```
// src/variations.js
import { registerBlockVariation } from '@wordpress/blocks';
import { __ } from '@wordpress/i18n';

registerBlockVariation('wpstack/product-showcase', {
    name: 'wpstack-featured-showcase',
    title: __('Featured Products Carousel', 'wpstack'),
    description: __('Display 4 featured products in a single row.', 'wpstack'),
    icon: 'star-filled',
    attributes: {
        selectedCategory: 'featured',
        postsPerPage: 4,
        columns: 4,
        showPrice: true,
        showRating: true,
        orderBy: 'popularity',
        order: 'desc',
    },
    scope: ['inserter', 'transform'],
});

registerBlockVariation('wpstack/product-showcase', {
    name: 'wpstack-clearance-grid',
    title: __('Clearance Bargain Grid', 'wpstack'),
    description: __('Display 12 discounted clearance items sorted by lowest price.', 'wpstack'),
    icon: 'tag',
    attributes: {
        selectedCategory: 'clearance',
        postsPerPage: 12,
        columns: 3,
        showPrice: true,
        showRating: false,
        orderBy: 'price',
        order: 'asc',
    },
    scope: ['inserter'],
});

```

## Custom Sidebar Panels with `@wordpress/plugins`

Editorial workflows often need a document-wide sidebar panel that checks post metadata, runs an SEO or accessibility checklist, or holds page-level settings. A dedicated sidebar plugin does the job:

```
// src/sidebar/index.jsx
import { registerPlugin } from '@wordpress/plugins';
import { PluginSidebar, PluginSidebarMoreMenuItem } from '@wordpress/editor';
import { PanelBody, TextControl, ToggleControl, SelectControl } from '@wordpress/components';
import { useSelect, useDispatch } from '@wordpress/data';
import { __ } from '@wordpress/i18n';

const WPStackEditorialSidebar = () => {
    const { postMeta } = useSelect((select) => ({
        postMeta: select('core/editor').getEditedPostAttribute('meta') || {},
    }));

    const { editPost } = useDispatch('core/editor');

    const handleMetaChange = (key, value) => {
        editPost({
            meta: {
                ...postMeta,
                [key]: value,
            },
        });
    };

    return (
        <>
            <PluginSidebarMoreMenuItem target="wpstack-editorial-sidebar" icon="admin-settings">
                {__('WPStack Workflow', 'wpstack')}
            </PluginSidebarMoreMenuItem>
            <PluginSidebar
                name="wpstack-editorial-sidebar"
                title={__('WPStack Workflow Controls', 'wpstack')}
                icon="admin-settings"
            >
                <PanelBody title={__('Editorial Metadata', 'wpstack')} initialOpen={true}>
                    <TextControl
                        label={__('Primary Keyword Target', 'wpstack')}
                        value={postMeta._wpstack_target_keyword || ''}
                        onChange={(val) => handleMetaChange('_wpstack_target_keyword', val)}
                        help={__('Target SEO keyword for content density checks.', 'wpstack')}
                    />

                    <ToggleControl
                        label={__('Mark as Sponsored / Affiliate', 'wpstack')}
                        checked={!!postMeta._wpstack_is_sponsored}
                        onChange={(val) => handleMetaChange('_wpstack_is_sponsored', val)}
                    />

                    <SelectControl
                        label={__('Publication Review Status', 'wpstack')}
                        value={postMeta._wpstack_review_status || 'draft'}
                        options={[
                            { label: __('Draft in Progress', 'wpstack'), value: 'draft' },
                            { label: __('Ready for Senior Review', 'wpstack'), value: 'ready_review' },
                            { label: __('Approved for Deployment', 'wpstack'), value: 'approved' },
                        ]}
                        onChange={(val) => handleMetaChange('_wpstack_review_status', val)}
                    />
                </PanelBody>
            </PluginSidebar>
        </>
    );
};

registerPlugin('wpstack-editorial-workflow', {
    render: WPStackEditorialSidebar,
});

```

## Core Web Vitals Results: ACF vs Static React vs Interactivity API

The table below is a qualitative comparison of three ways to render 10 dynamic product cards on a busy WooCommerce store. It reflects how each approach ships JavaScript and markup, not measured results:

| Architecture / Rendering Pattern | Total Blocking Time (TBT) | Interaction to Next Paint (INP) | Frontend JS Weight | DOM Nodes Count | Lighthouse Score |
| --- | --- | --- | --- | --- | --- |
| **Legacy ACF PHP Block (Uncached)** | Moderate | Highest (Poor) | Moderate (jQuery + CSS) | Moderate | Moderate |
| **Static React Client-Rendered Block** | Highest | Moderate (Needs Work) | Highest (React/ReactDOM) | Highest | Lowest |
| **Modern Interactivity API (Block API v3)** | **Lowest** | **Lowest (Good)** | **Lowest (Shared Runtime)** | **Lowest** | **Highest** |

**Block API v3 with the WordPress Interactivity API** is usually the strongest option for Core Web Vitals, because the shared Interactivity runtime is far smaller than shipping React to the front end and only the interactive parts of the page are hydrated.

## How Blocks Hydrate on the Client and Delegate Events

How static HTML becomes interactive UI matters a great deal on busy sites. With full-page React hydration (as in Next.js, or Astro before islands), the browser downloads the whole component tree, runs JavaScript to build a virtual DOM and attaches listeners to every node.

On content-rich WordPress pages with 40+ interactive blocks (product carousels, FAQ accordions, tabs, filter dropdowns), full hydration becomes a CPU bottleneck and can push **Total Blocking Time (TBT)** past 300ms on mobile.

The **WordPress Interactivity API** avoids this with *progressive selective hydration* and *event delegation* at the root:

1. **No virtual DOM:** It never builds a synthetic DOM in memory. Reactive signals (Preact Signals) are bound straight to existing elements marked with `data-wp-*` directives.
2. **Delegated events:** Instead of one listener per button, which eats heap memory, core attaches a single document-level listener for each event type (`click`, `change`, `input`). Events bubble to that root, which finds the matching store action and runs it.
3. **Hydration when idle:** Stores hydrate during browser idle time via `requestIdleCallback()`, so JavaScript never blocks the Largest Contentful Paint.

## Troubleshooting Guide for Production Incidents

| Incident / Symptom | Root Cause | Immediate Remediation CLI / Code Fix |
| --- | --- | --- |
| Editor error: `Block validation failed` | Static `save.js` markup modified in plugin update without creating a block deprecation | Convert block to dynamic rendering via `render.php` and set `save: () => null` |
| Gutenberg sidebar freezes on open | `useEntityRecords` or `apiFetch` re-executing inside un-memoized React render hook | Wrap selector in `useSelect((select) => …)` and check dependency arrays |
| REST API returns 401 Unauthorized in Editor | Custom REST route missing `permission_callback` allowing `current_user_can(‘edit_posts’)` | Ensure `permission_callback` validates standard logged-in editor capabilities |
| Styling broken in Editor vs Frontend | Editor canvas rendered inside iframe in API v3 but styles loaded in outer DOM | Specify `”editorStyle”: “file:./build/index.css”` in `block.json` for iframe injection |
| Slow page TTFB with dynamic blocks | `render.php` executing unindexed SQL queries (`SQL_CALC_FOUND_ROWS`) per block | Add `’no_found_rows’ => true` to `WP_Query` and wrap HTML output in `wp_cache_set()` |

## Automated Tests with Jest and PHPUnit

### 1. Testing the Edit Component with Jest

```
// __tests__/edit.test.jsx
import { render, screen, fireEvent } from '@testing-library/react';
import Edit from '../src/edit';

// Mock WordPress dependencies
jest.mock('@wordpress/core-data', () => ({
    useEntityRecords: () => ({
        records: [
            { id: 10, name: 'Shoes', count: 5 },
            { id: 11, name: 'Apparel', count: 12 },
        ],
        hasResolved: true,
    }),
}));

jest.mock('@wordpress/block-editor', () => ({
    useBlockProps: () => ({ className: 'wpstack-mock-block' }),
    InspectorControls: ({ children }) => <div data-testid="inspector-controls">{children}</div>,
}));

jest.mock('@wordpress/server-side-render', () => () => <div data-testid="ssr-preview">SSR Preview</div>);

describe('ProductShowcase Edit Component', () => {
    it('renders inspector controls and passes updated attributes', () => {
        const mockSetAttributes = jest.fn();
        const attributes = {
            selectedCategory: 'all',
            postsPerPage: 6,
            columns: 3,
            showPrice: true,
            showRating: true,
            orderBy: 'date',
            order: 'desc',
        };

        render(<Edit attributes={attributes} setAttributes={mockSetAttributes} />);

        expect(screen.getByTestId('ssr-preview')).toBeInTheDocument();
        expect(screen.getByTestId('inspector-controls')).toBeInTheDocument();
    });
});

```

### 2. Testing Rendered Output with PHPUnit

```
namespace WPStack\Tests;

use WP_UnitTestCase;

final class BlockRendererTest extends WP_UnitTestCase {
    public function test_dynamic_renderer_outputs_expected_wrapper(): void {
        // Create mock product
        $product_id = $this->factory->post->create([
            'post_title' => 'Test Premium Plugin',
            'post_type'  => 'product',
            'post_status' => 'publish',
        ]);

        $attributes = [
            'selectedCategory' => 'all',
            'postsPerPage'     => 4,
            'columns'          => 2,
            'showPrice'        => true,
            'showRating'       => false,
            'orderBy'          => 'date',
            'order'            => 'desc',
        ];

        ob_start();
        include dirname(__DIR__) . '/render.php';
        $output = ob_get_clean();

        $this->assertStringContainsString('wpstack-product-grid columns-2', $output);
        $this->assertStringContainsString('Test Premium Plugin', $output);
    }
}

```

## Need Help Building Custom Gutenberg Blocks?

Block-based sites can support custom publishing workflows, WooCommerce landing pages and full design systems. MoxSEO’s web development team builds and audits custom WordPress blocks, plugins and integrations, including Block API v3 libraries and Interactivity API components.

If you need custom Gutenberg blocks, a design system refactor or a migration away from legacy ACF blocks, see our [WordPress development services](/services/web-development/wordpress/).

## Common questions

### What is Block API v3 in Gutenberg?

It is the current block specification. It renders the editor canvas in an isolated iframe, supports native ES modules, standardizes `block.json` declarations and works with the Interactivity API.

### Why does changing static block HTML trigger “Block validation failed”?

A static block (`save.js`) is checked by comparing the HTML stored in the database with what the current `save()` function outputs. Any difference in tags, attributes or whitespace fails validation unless you ship a block deprecation migration.

### How does `useEntityRecords` stop infinite REST fetch loops?

It keeps results in Redux-backed state, so several components that ask for the same entities share one cached response rather than repeating HTTP calls on each render.

### What does `get_block_wrapper_attributes()` do in `render.php`?

It builds the outer container’s attributes for you: core style classes, custom class names, inline styles (padding, margin, background color) and the HTML ID the author set.

### How can I limit which blocks go inside `InnerBlocks`?

Give the `allowedBlocks` prop an array of block names, for example `[‘core/heading’, ‘core/paragraph’]`, and optionally add a `template` array for the starting layout.

### Is TypeScript supported for custom blocks?

Yes. `@wordpress/scripts` compiles TypeScript out of the box, so you can write `src/edit.tsx` and `src/index.ts` with full type checking.

### How do I clear cached dynamic block output when a product or post changes?

Hook `save_post_product` or `edit_product_cat` in PHP and call `wp_cache_delete()` or a transient purge routine to remove the related showcase cache keys right away.

### What does `’no_found_rows’ => true` do in block queries?

Setting `’no_found_rows’ => true` stops MySQL from running `SQL_CALC_FOUND_ROWS`, so it skips the pagination total, which can noticeably reduce query time on large tables when you do not need pagination.
