Source Directory
Hooks

React & Custom Hooks

A compilation of some most-used hooks that come with React out of the box. Specific details can be found on react.dev (opens in a new tab).

Note that when working with WordPress Gutenberg we should be pulling all React hooks from the @wordpress/element package instead of directly from React as the WordPress versions of React and Latest version of React differ.

⚠️

Note that some hooks may not be available to Gutenberg since WordPress's React dependency version may differ. A list of those can be found in the Block Editor Handbook (opens in a new tab).

useState

A React Hook that lets you add a state variable (opens in a new tab) to your component.

const [state, setState] = useState(initialState)

useEffect

A React Hook that lets you synchronize a component with an external system (opens in a new tab).

useEffect(() => {
  // Mutate values here.
  () => {
    // Close out the lifecycle here.
  }
}, [ dependenciesArrayValues ])

useMemo

A React Hook that lets you cache the result of a calculation between re-renders.

const cachedValue = useMemo(calculateValue, dependencies)

useCallback

A a React Hook that lets you cache a function definition between re-renders.

const cachedFn = useCallback(fn, dependencies)

useRef

A a React Hook that lets you reference a value that’s not needed for rendering.

const ref = useRef(initialValue)

Gutenberg Hooks

A compilation of most-used custom hooks available in the core gutenberg plugin. We can get other information directly about the current post from the core/editor (opens in a new tab) suite of functions.

useSelect

The useSelect hook replaces the withSelect higher-order component available in the core/data (opens in a new tab) package.

This may be arguable one of the most-used hooks when building for Goots™. useSelect allows for a continual update of a value based on React renders or some change in dependency defined in the dependency array (like useEffect).

Example The example below gets all posts for a custom post type and returns only the id and title fields.

import { useSelect } from '@wordpress/data';
 
/**
 * Fetch all posts.
 */
const allPosts = useSelect(
	( select ) => select( 'core' ).getEntityRecords(
		'postType',
		'post',
		{ per_page: -1, _fields: 'id,title' }
	) || [],
);

useDispatch

The useDispatch hooks replaces the withDispatch higher-order component available in the core/data (opens in a new tab) package.

useDispatch provides direct access to the current registry dispatch action creators meaning we are provided several functions in which to update the WordPress-flavored Redux Store (opens in a new tab) where our "entities" exist.

Example The example below updates the category for the current post. The editPost function assumes the current post.

import { useDispatch } from '@wordpress/data';
 
/**
 * Dispatcher
 */
const { editPost } = useDispatch( 'core/editor' );
 
/**
 * Can be used in a callback or useEffect hook.
 */
editPost({ category: [ 10 ] });

useBlocksByName

A hook that returns the current editor blocks by name.

The block name + namespace blockName value required.

Usage

	const headings = useEditorHeadings( 'core/heading' );

useBlocksByName

Get all editor blocks by name.

  • blockName: string — Block name to search for.

useDebounce

A custom React hook that creates and returns a new debounced version of the passed value that will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked.

Usage

const MyComponent = () => {
  const [value, setValue] = useState('');
  const debouncedValue = useDebounce(value, 500);
 
  // This value will display after 500 milliseconds
  useEffect(() => {
    // Kickoff Function on a delay.
  }, [debouncedValue]);
 
  return (
    <>
      <TextControl
        label={__('Set Value', 'pmc-gutenberg')}
        onChange={(next) => setValue(next)}
        value={value}
      />
    </>
  );
};

useDebounce

Debounce return of a value.

  • value: mixed — Value to debounce.
  • delay: — Debounce increment in ms.

useDelay

A simple hook to return a boolean based on whether or not a delay has happened. Default 2500 seconds.

Usage

const MyComponent = () => {
  const isDelayed = useDelay(500);
 
  // This value will be true after 500 milliseconds
  console.log(isDelayed);
};

useDelay

Returns when delay has occurred.

  • delay: int — Debounce increment in ms.

Experimental Features

A collection of hooks and methods for interacting with the feature flag system.

useGetFeatureFlags

Get global feature flag config array or specific subset of values.

useFlagEnabled

Get status of a feature flag for a given slug.

  • slug: string — Feature flag slug.

flagEnabled

Get status of a feature flag for a given slug. For use in non-React instances.

  • slug: string — Feature flag slug.

useGlobalConfig

A hook to return the value of the pmc_gutenberg_config_script localized script, filterable by themes and plugins.

Usage

All configs.

const allConfigs = useGlobalConfig();

A specific config.

const specificConfig = useGlobalConfig( 'specific-config' );

Returns

Returns an array of objects (all) or an object (mixed value, specified).

useGlobalConfig

Get global config array or specific subset of values.

  • key: ?string — Optional specified key.
  • defaultValue: mixed — Default value to return.

useInnerBlocks

A hook that returns the current block's innerblock objects, aka child blocks.

Parent block clientId value required.

Usage

	const blocks = useInnerBlocks( clientId );

useInnerBlocks

UseInnerBlocks hook..

  • clientId: string — Clinet id unique for a block.

useInnerBlockAttributes

A hook that returns the current blocks innerblock attributes. Used in conjunction with the useInnerBlocks custom hook.

Parent block clientId value required.

Usage

	const blocksAttributes = useInnerBlocksAttributes( clientId );

useInnerBlocksAttributes

Get the innerBlocks attributes object for innerBlock children.

  • clientId: string — Block client id.

useInnerBlockAttributes

A hook that returns the current blocks innerblock attributes. Used in conjunction with the useInnerBlocks custom hook.

Parent block clientId value required.

Usage

	const innerBlockCount = useInnerBlocksCount( clientId );

useInnerBlocksCount

Get the count of innerblocks.

  • clientId: string — Block client id.

useLocalStorage

A hook to get and set local storage values by key.

Usage

const [ value, setLocalStorage ]= useLocalStorage( key, initialValue );

getStorageValue

Get local storage helper.

  • key: string — Local storage key.
  • defaultValue: mixed — Default value for local storage.

useLocalStorage

Hook to return local storage value by key.

  • key: string — Local storage key.
  • defaultValue: mixed — Default value for local storage.

useNovaCards

A reducer for handling NovaCard and NovaCards interactions.

addCardAfter

Insert an additional card object after a given index.

  • cardsObject: Object — Cards object.
  • action: Object — Action object.

addCardBefore

Insert an additional card object before a given index.

  • cardsObject: Object — Cards object.
  • action: Object — Action object.

addCard

Insert a new card object at the provided index, or at the end of the cards array.

  • cardsObject: Object — Cards object.
  • action: Object — Action object.

fixCardCount

If the cards array has too many or too few card objects, insert or remove cards as needed.

  • cardsObject: Object — Cards object.
  • action: Object — Action object.

moveCardDown

Swap card position with the following card.

  • cardsObject: Object — Cards object.
  • action: Object — Action object.

moveCardUp

Swap card position with the previous card.

  • cardsObject: Object — Cards object.
  • action: Object — Action object.

removeCard

Remove card.

  • cardsObject: Object — Cards object.
  • action: Object — Action object.

removeLastCard

Remove the last card.

  • cardsObject: Object — Cards object.
  • action: Object — Action object.

setBackfill

Set card's backfill.

  • cardsObject: Object — Cards object.
  • action: Object — Action object.

setCardsInfo

Set Additional information from cards like title, description, button etc...

  • cardsObject: Object — Cards object.
  • action: Object — Action object.

setVisibility

Set card's details visibility.

  • cardsObject: Object — Cards object.
  • action: Object — Action object.

updateCard

Update a card object.

  • cardsObject: Object — Cards object.
  • action: Object — Action object.

reducer

Action dispatcher.

  • state: Object — State object.
  • action: Object — Action to dispatch.

useNovaCards

Novacard hook helper.

  • props0: Object — Props object.
  • props0.attributes: Object — Attributes object.
  • props0.attributesKey: string — Attribute key.
  • props0.range: string|int — Index range.
  • props0.setAttributes: func — Attributes setter.

canAddCardAfter

  • cardsObject: Object — Cards object.
  • options: Object — Selector options object.

canAddCardBefore

  • cardsObject: Object — Cards object.
  • options: Object — Selector options object.

canAddCard

  • cardsObject: Object — Cards object.
  • options: Object — Selector options object.

canMoveCardDown

  • cardsObject: Object — Cards object.
  • options: Object — Selector options object.

canMoveCardUp

  • cardsObject: Object — Cards object.
  • options: Object — Selector options object.

canRemoveCard

  • cardsObject: Object — Cards object.
  • options: Object — Selector options object.

getMaxAllowedCards

Get the maximum amount of cards required.

  • cardsObject: Object — Cards object.
  • options: Object — Selector options object.

getMinAllowedCards

Get the minimum amount of cards required.

  • cardsObject: Object — Cards object.
  • options: Object — Selector options object.

hasValidCardCount

  • cardsObject: Object — Cards object.
  • options: Object — Selector options object.

useOnScreen

Uses an IntersectionObserver to determine if the element is visible in the viewPort or not.

Usage

const ref = useRef(null);
const isVisible = useOnScreen( ref?.current );

Props

ref reference from the element.

useOnScreen

Determine if a block is visible in the viewport or not.

  • ref: Object — Reference object.

Use Post Terms

Return term objects for a post/post type and taxonomy slug, if supported.

Usage

const [ postTerms, hasPostTerms, isLoading ] = usePostTerms( postId, postType, term );

Params

  • postId post id of the current post.
  • postType post type of the current post.
  • term term object to retrieve term objects for.

usePostTypeTemplate

Retrieves the post type template from the global config array. See pmc-gutenberg and the classes/editor/class-gutenberg-helpers.php line 41 and the use of the pmc_gutenberg_config_script.

Usage

const [ data, version ] = usePostTypeTemplate();

Returns

Expected return would be the data: array of arrays (InnerBlocks template), and the template version string.

const rawValues = {
	'data'    => [ [ ... ] ],
	'version' => '0.0.1',
}

Setup

Extends the pmc_gutenberg_filter_localize_gutenberg_config filter. Expects a return of version and data.

usePrevious

A hook to store the previous state for a value.

Usage

const oldValue = usePrevious( value );

usePrevious

Store the previous value for return.

  • value: mixed — Old value.

useTaxonomy

Hook to return a custom taxonomy term by slug.

Usage

const taxonomy = useTaxonomy( 'post_tag', [] );

Params

  • slug term slug.
  • dependencies dependency array.

useTaxonomy

Get the taxonomy object for the selected term.

  • slug: string — Term slug.
  • dependencies: Array — Dependency array.
  • taxVisibilityIgnore: boolean — Ignore Taxonomy visibility.
  • Reference (opens in a new tab)

useTemplateKeys

Helper hook to return an element and section key in the formatted expected by backfill.

Usage

const [ elementKey, sectionKey ] = useTemplateKeys(
	clientId,
	attributesKey,
	mapTo
);

Props

proptyperequireddescription
clientIdstringyesBlock clientId from props.
attributesKeystringyesDefining key for attributes cards object.
mapTostringyesUnique identifier.

useTemplateKeys

Return template and section key from values.

  • clientId: string — Block client id.
  • cardKey: string — Cards section key.
  • mapTo: string — Unique mapTo key.

useUserHasRole

Determine if a user has a defined role.

Usage

const hasRole = useUserHasRole( 'userRole' );

Params

  • userRole user role.

useUserHasRole

Helper to check if current user has the given role.

  • userRole: string — User role to check.

Use Window Size

Returns the window height and width returned as a tuple.

Usage

const App = () => {
	const [height, width] = useWindowSize();
 
	return (...)
}

useWindowSize

Returns array of height and width in [ height, width ] format.