Creating custom react hooks for wordpress api interactions example

Learn how to create powerful custom React hooks to interact with the WordPress REST API for fetching, caching, and updating data in your headless WordPress projects.

Meta description: Learn how to create powerful custom React hooks to interact with the WordPress REST API for fetching, caching, and updating data in your headless WordPress projects.

Introduction

Modern frontend development often demands seamless integration with backend APIs, especially when working with content-rich platforms like WordPress. With the rise of headless CMS architectures, the WordPress REST API has become an essential tool for developers who want to decouple the frontend and backend layers.

In this guide, we’ll explore how to create custom React hooks to interact with the WordPress REST API. We’ll walk through fetching posts, implementing caching, updating content, and securing API calls. By the end, you’ll be equipped with reusable, performant, and scalable solutions for building modern frontends with React and WordPress integration.

What Are Custom React Hooks?

Custom React hooks are JavaScript functions that start with use and let you extract and reuse stateful logic between components. Hooks like useState and useEffect serve as the foundation for building custom ones. With these tools, developers can keep code modular, improve readability, and enhance reusability.

Why Use the WordPress REST API?

  • Enables headless WordPress development.
  • Allows React applications to fetch and manipulate WordPress data.
  • Facilitates decoupled frontend/backend architectures.

Benefits of Using Custom Hooks for WordPress API

  • Code Reusability: Avoid duplicate logic across components.
  • Performance: Integrate caching mechanisms.
  • Separation of Concerns: Keep UI logic separate from data fetching logic.

Want to learn more about hooks? Check out the React Hooks documentation.


Step 1: Setting Up Your WordPress REST API for External Access

To start using the WordPress REST API, ensure your site is publicly accessible and the REST API is enabled.

Basic Requirements:

  • A self-hosted WordPress site (or WordPress.com with REST API enabled).
  • Permalinks should be set to anything except “Plain”.

Check if It’s Working:

Visit:https://yourdomain.com/wp-json/wp/v2/posts

You should see a JSON response of your latest posts.

For more info, refer to the WordPress REST API Handbook.

Creating a Simple Hook to Fetch Posts

We’ll build a useFetchPosts custom hook using useState and useEffect to fetch WordPress data in React.

// hooks/useFetchPosts.js
import { useState, useEffect } from 'react';

export const useFetchPosts = (endpoint = '/wp-json/wp/v2/posts') => {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(endpoint);
        if (!response.ok) throw new Error('Network response was not ok');
        const data = await response.json();
        setPosts(data);
      } catch (err) {
        setError(err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [endpoint]);

  return { posts, loading, error };
};

How to Use It in a Component.

 import React from 'react';
import { useFetchPosts } from './hooks/useFetchPosts';

const PostList = () => {
  const { posts, loading, error } = useFetchPosts();

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <ul>
      {posts.map(post => (
        <li key={post.id}>{post.title.rendered}</li>
      ))}
    </ul>
  );
};

Implementing Caching with localStorage or SWR.

export const useCachedFetchPosts = (endpoint = '/wp-json/wp/v2/posts') => {
  const [posts, setPosts] = useState(() => {
    const cached = localStorage.getItem('posts');
    return cached ? JSON.parse(cached) : [];
  });
  const [loading, setLoading] = useState(posts.length === 0);

  useEffect(() => {
    if (posts.length === 0) {
      fetch(endpoint)
        .then(res => res.json())
        .then(data => {
          localStorage.setItem('posts', JSON.stringify(data));
          setPosts(data);
          setLoading(false);
        });
    }
  }, [endpoint]);

  return { posts, loading };
};

Using SWR (recommended for production)

npm install swr
import useSWR from 'swr';
const fetcher = url => fetch(url).then(res => res.json());

export const useSWRPosts = () => {
  const { data, error, isLoading } = useSWR('/wp-json/wp/v2/posts', fetcher);

  return {
    posts: data || [],
    loading: isLoading,
    error,
  };
};

Creating a POST Hook to Update WordPress Content

For authenticated requests (like creating or updating posts), use Axios.

Using Axios for WordPress API

npm install axios
export const useCreatePost = (token) => {
  const [status, setStatus] = useState(null);

  const createPost = async (title, content) => {
    try {
      const res = await axios.post('/wp-json/wp/v2/posts', {
        title,
        content,
        status: 'publish',
      }, {
        headers: {
          Authorization: `Bearer ${token}`
        }
      });
      setStatus('success');
    } catch (err) {
      setStatus('error');
    }
  };

  return { createPost, status };
};

Error Handling and Loading States

Always include state management for loading and error messages in your hooks to improve UX.

// Already implemented in the examples above
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;

Securing API Calls with Authentication Tokens

Option 1: Application Passwords (Simpler)

  • Go to WordPress > Users > Your Profile.
  • Generate an application password.
  • Use it for basic auth: username:application-password.

Option 2: JWT Authentication

  • Install JWT Auth plugin.
  • Use /wp-json/jwt-auth/v1/token to get a token.
  • Pass the token in Authorization headers.
Authorization: Bearer <your-token>
reactpress

By building custom hooks for WordPress, React developers can create more efficient, clean, and scalable frontends. Whether you’re developing a headless blog, a news site, or a WooCommerce dashboard, mastering this integration gives you the power of WordPress with React.

Read from basic click here.

Leave a Comment

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