Thunks for WordPress Developers: Mastering Deferred Logic in Gutenberg and Beyond

Introduction

A photorealistic image of a WordPress developer coding a Gutenberg plugin using JavaScript on a widescreen monitor. The screen shows a custom sidebar panel and block editor interface. A flowchart on the wall illustrates thunk-based asynchronous data management between selector, thunk, and reducer.

WordPress has evolved from a PHP-centric content management system into a modern JavaScript-driven application platform. With the rise of the Gutenberg block editor, many WordPress developers are now writing JavaScript—particularly React—and bumping into new concepts like thunks.

But what is a thunk? And how can understanding it improve your custom block development, plugin architecture, or REST API interactions?

In this article, we’ll break it down for WordPress developers:

  • What thunks are and how they work
  • Where they show up in Gutenberg
  • Practical examples from WordPress core and custom development
  • When to use thunks vs other asynchronous strategies

What Is a Thunk?

thunk is a function that wraps an operation in a parameterless function to defer execution. Instead of immediately performing a calculation, fetching data, or calling an API, a thunk returns a function that will do it—when you’re ready.

Simplified Example (JavaScript)

// Immediate execution
const result = expensiveCall();

// Thunk pattern
const thunk = () => expensiveCall();

Calling thunk() executes expensiveCall(). Until then, it’s dormant.

View Simplified Example (JavaScript) on GitHub.

In Gutenberg, this pattern allows you to postpone actions—like updating the store or calling an API—until you’ve confirmed user intent or completed validation.

Thunks in Gutenberg and WordPress

Gutenberg uses Redux-style data stores, which means thunks are baked right into WordPress core. The @wordpress/datapackage supports asynchronous action creators via thunks.

Example: Fetching Posts Using a Thunk

import { dispatch } from '@wordpress/data';

dispatch('core').fetchEntityRecords( 'postType', 'post', { per_page: 5 } );

View Fetching Posts Using a Thunk on GitHub.

Behind the scenes, fetchEntityRecords is a thunk. It returns a function that performs the actual REST API call and updates the store when the results arrive.

This enables:

  • Non-blocking UI
  • Clean separation between action declaration and execution
  • Hook-based data fetching (useSelect) that tracks the request lifecycle

Building Your Own Custom Thunk

Suppose you’re building a custom plugin or sidebar panel and want to write to the WordPress store or fetch external data:

import { dispatch } from '@wordpress/data';

const saveCustomData = (data) => {
	return ( { select, dispatch } ) => {
		const store = dispatch('my-plugin/store');
		store.setSaving(true);

		fetch('/wp-json/my-plugin/v1/save', {
			method: 'POST',
			body: JSON.stringify(data),
			headers: { 'Content-Type': 'application/json' },
		})
			.then((res) => res.json())
			.then((response) => store.setSaving(false));
	};
};

// Dispatch the thunk
dispatch('my-plugin/store').saveCustomDataThunk();

View Building Your Own Custom Thunk on GitHub.

This thunk:

  1. Defers the fetch call
  2. Manages state transitions cleanly (e.g. loading indicators)
  3. Integrates tightly with Gutenberg’s reactive data model

Why WordPress Developers Should Care

You don’t need to know the term “thunk” to write Gutenberg blocks—but knowing how and when to use them can level up your development in key ways:

  1. Control Side Effects
    Wrap fetch calls, validation, or complex business logic inside thunks to keep UIs declarative.
  2. Compose Async Logic
    Chain multiple steps (e.g. fetch → validate → save) within a single thunk to maintain clarity and control.
  3. Improve Testability
    Thunks are pure functions until invoked—great for mocking in unit tests.
  4. Conform to Core Practices
    WordPress core uses thunks extensively in its block editor and REST handling. Learning the

Thunks vs Promises vs Async/Await

You might wonder: “Why not just use Promises or async/await?”

They’re all useful—but thunks offer deferred execution. Promises are eager; they run immediately. Thunks only run when dispatched.

That deferred behavior makes them ideal for middleware, store management, and conditional logic—hallmarks of Gutenberg and the REST API layer.

Summary: Key Takeaways for WordPress Developers

  • thunk is a function that delays execution by wrapping logic in a parameterless function.
  • Gutenberg supports thunks via the @wordpress/data package to manage async actions in Redux-style stores.
  • Use thunks to manage side effects like API calls, loading states, and custom save handlers.
  • Thunks fit naturally into modern WordPress development with blocks, stores, and REST endpoints.
  • Understanding thunks helps you build scalable, maintainable plugins and interfaces aligned with WordPress core practices.

Next Steps

    • Explore @wordpress/data documentation
    • Review how core blocks use selectors and dispatchers (e.g. useSelect, useDispatch)
    • Refactor your async handlers in plugins to use thunks for clarity and testability

    Reader Interactions

    Leave a Reply

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