WordPress Gutenberg useEffect: Fetch Data, Debounce Inputs, and Clean Up Side Effects in Blocks

useEffect in custom blocks: fetch data, debounce input, clean up

The edit function of a block is a React component. When it needs data from the server, for example the title of a feed whose URL the editor typed, the request belongs in useEffect: it runs after rendering, can depend on attributes, and can clean up after itself. The two things to get right are not sending a request on every keystroke, and not applying the answer of an old request after a newer one.

Problem: A block has a “Feed URL” field. When it changes, the block should load the feed’s title from a custom REST route and show it, but not on every keystroke, and an old, slower answer must not overwrite a newer one.

Solution: Use useEffect with the URL as the dependency, delay the request with setTimeout, cancel the timer and the request with an AbortController in the effect’s cleanup function, and call the REST API with apiFetch.

The edit component

The example uses JSX and a build with @wordpress/scripts:

import { useEffect, useState } from '@wordpress/element';
import { useBlockProps, InspectorControls } from '@wordpress/block-editor';
import { PanelBody, TextControl, Spinner } from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';
import { addQueryArgs } from '@wordpress/url';

export default function Edit( { attributes, setAttributes } ) {
    const { feedUrl, feedTitle } = attributes;
    const [ loading, setLoading ] = useState( false );

    useEffect( () => {
        if ( ! feedUrl ) {
            return;
        }

        const controller = new AbortController();

        const timer = setTimeout( () => {
            setLoading( true );

            apiFetch( {
                path: addQueryArgs( '/ha/v1/feed-title', { url: feedUrl } ),
                signal: controller.signal
            } )
                .then( ( data ) => setAttributes( { feedTitle: data.title } ) )
                .catch( ( error ) => {
                    if ( error.name !== 'AbortError' ) {
                        setAttributes( { feedTitle: '' } );
                    }
                } )
                .finally( () => setLoading( false ) );
        }, 500 );

        // Runs before the next effect and when the block is removed
        return () => {
            clearTimeout( timer );
            controller.abort();
        };
    }, [ feedUrl ] );

    return (
        <div { ...useBlockProps() }>
            <InspectorControls>
                <PanelBody title="Feed">
                    <TextControl
                        label="Feed URL"
                        value={ feedUrl || '' }
                        onChange={ ( value ) => setAttributes( { feedUrl: value } ) }
                    />
                </PanelBody>
            </InspectorControls>
            { loading ? <Spinner /> : <p>{ feedTitle || 'Enter a feed URL in the block settings.' }</p> }
        </div>
    );
}

Every keystroke changes feedUrl, so React runs the cleanup of the previous effect (the timer is cancelled) and starts a new one. Only when typing stops for 500 ms does a request go out, and if the URL changes while it is running, abort() cancels it.

apiFetch adds the REST nonce and the site’s API root automatically, which a plain fetch() does not.

The dependency array

  • [ feedUrl ]: run when the URL changes (and on the first render).
  • []: run once, when the block is mounted, for data that does not depend on attributes.
  • No array: run after every render, which is almost never what you want and easily ends in an endless loop when the effect sets state.

Server side

The REST route fetches the feed on the server, where there is no CORS problem and the response can be cached:

<?php
add_action( 'rest_api_init', function () {
    register_rest_route( 'ha/v1', '/feed-title', array(
        'methods'             => 'GET',
        'permission_callback' => function () {
            return current_user_can( 'edit_posts' );
        },
        'args'                => array( 'url' => array( 'type' => 'string', 'format' => 'uri', 'required' => true ) ),
        'callback'            => function ( WP_REST_Request $request ) {
            $feed = fetch_feed( $request['url'] ); // SimplePie, cached for 12 hours
            if ( is_wp_error( $feed ) ) {
                return $feed;
            }
            return array( 'title' => $feed->get_title() );
        },
    ) );
} );

NOTE: Do not call setAttributes() for data that is only needed for the preview: attributes are saved into the post content. Here the feed title is meant to be saved; a list of feed items for a preview should live in useState instead.