Debouncing is a term in software development that is used to prevent a function to run until a specific time has elapsed, which significantly improves the cost. Cost in the terms of requests. Example: let’s say we have a search box that calls an API request on change of the search box to display the live results to the users.

Users search the term: Mango. When you enter M it’s 1 request, a it’s 1 request, n it’s 1 request, and so on. Therefore costing more API requests instead of just 1.

In WordPress, while creating settings for the block using block controls, we often create the input boxes which render the data from the server side on the change of that input box.

<TextControl
    label={ __( 'Keywords', 'aawp' ) }
    value = {keywords}
    placeholder = {__( 'Enter keywords here. E.g. "top 4k monitors"', 'aawp') }
    onChange= { (value) => setAttributes( { keywords: value } ) }
 />;

In the code snippet above, whenever we enter a character in the input box, it starts to render data from the server side using ServerSideRender from an API with the snippet below:

<ServerSideRender
   key="aawp-server-side-renderer"
   block="aawp/aawp-block"
   attributes={ props.attributes }
/>

However, ServerSideRender Shouldn’t be used for building new features. It’s now a legacy approach – and it doesn’t have a nice easy way to work with debouncing for the reason below.

setAttributes update TextControl value and in turn, TextControl is refreshed and updated only when attributes are changed. It means that if TextControl is refreshed, ServerSideRender will be refreshed as well, which is slow.

https://wordpress.stackexchange.com/a/412148/200225

The solution is to code the PHP rendering logic in react.

debounce() function of Loadash can be used. All of Lodash will always be loaded anyways by @wordpress/element, or better use usedebounce() – A simplified and properly typed version of lodash’s debounce

ServerSideRenderer is debounced anyway by half a second. Ref: WordPress/gutenberg#7320

Debouncing – preventing a function to run instantly in React
Tagged on:     

Sanjeev Aryal

Don't bury your thoughts, put your vision into reality ~ Bob Marley.

Leave a Reply

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

× WhatsApp