Blog>
Snippets

Utilizing React Hooks with the WordPress Data Module

Demonstrate the use of `useSelect` and `useDispatch` hooks to bind a React component’s local state to the WordPress data store.
import { useSelect, useDispatch } from '@wordpress/data';
import { useEffect, useState } from 'react';

function MyCustomComponent() {
    // Use useSelect to subscribe to the WordPress data store and retrieve state.
    const posts = useSelect((select) => {
        // Use a selector to get data from the store. For example, to get posts.
        return select('core').getEntityRecords('postType', 'posts', { per_page: 10 });
    }, []);

    // Use useDispatch to get the dispatch function for the store.
    const { savePost } = useDispatch('core/editor');

    // Local component state
    const [content, setContent] = useState('');

    // Example of useEffect to handle side-effects.
    useEffect(() => {
        // Do something when posts data changes.
        // For example, set content to the title of the first post.
        if (posts && posts.length) {
            setContent(posts[0].title.rendered);
        }
    }, [posts]);

    const handleSave = () => {
        // Use dispatch action to interact with the store.
        // For example, this may trigger saving a post.
        savePost();
    };

    return (
        <div>
            <textarea
                value={content}
                onChange={(e) => setContent(e.target.value)}
            />
            <button onClick={handleSave}>Save Post</button>
        </div>
    );
}

export default MyCustomComponent;
This code defines a functional React component called MyCustomComponent. Within the component, the useSelect hook is used to get a list of posts from the WordPress data store. The useDispatch hook is used to access the savePost action from the 'core/editor' store. The component maintains its own local state, content, using useState. An effect hook (useEffect) is used to perform side effects based on changes to the posts data fetched from the store, such as updating the local content state when the list of posts changes. The handleSave function demonstrates using a dispatch action to save a post when a button is clicked. The return statement renders a textarea bound to the local content state and a button to trigger the save action.