Prompt
How do I use a headless CMS with React?
Latest observation
Using a headless CMS with React is a common way to separate your content from your frontend app.
What it means
- Headless CMS = a backend for managing content without controlling the frontend.
- React = your frontend that fetches content from the CMS via API.
Typical flow:
- You create/edit content in the CMS.
- The CMS exposes that content through REST or GraphQL APIs.
- Your React app fetches the content and renders it.
Basic steps
1) Pick a headless CMS
Popular options:
- Contentful
- Sanity
- Strapi
- Prismic
- Storyblok
- Directus
Some are SaaS, some are self-hosted.
2) Model your content
For example, if you're building a blog, you might create:
Post- title
- slug
- body
- author
- coverImage
- publishedDate
3) Create content in the CMS
Add a few entries so you can test the API.
4) Fetch content in React
You’ll usually use fetch or axios inside a component, custom hook, or data-fetching library.
Example using fetch
import { useEffect, useState } from "react";
function BlogPosts() {
const [posts, setPosts] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function loadPosts() {
try {
const res = await fetch("https://api.example-cms.com/posts");
const data = await res.json();
setPosts(data);
} catch (error) {
console.error("Error loading posts:", error);
} finally {
setLoading(false);
}
}
loadPosts();
}, []);
if (loading) return <p>Loading...</p>;
return (
<div>
{posts.map((post) => (
<article key={post.id}>
<h2>{post.title}</h2>
<p>{post.excerpt}</p>
</article>
))}
</div>
);
}
export default BlogPosts;
5) Render the content
Use the returned data to build pages, cards, lists, detail views, etc.
If you’re using GraphQL
Some CMSs provide GraphQL APIs.
import { useEffect, useState } from "react";
function BlogPosts() {
const [posts, setPosts] = useState([]);
useEffect(() => {
async function loadPosts() {
const res = await fetch("https://api.example-cms.com/graphql", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
query: `
query {
posts {
id
title
excerpt
}
}
`,
}),
});
const result = await res.json();
setPosts(result.data.posts);
}
loadPosts();
}, []);
return (
<div>
{posts.map((post) => (
<h2 key={post.id}>{post.title}</h2>
))}
</div>
);
}
Useful patterns
Custom hook
Keep data-fetching logic reusable:
import { useEffect, useState } from "react";
export function usePosts() {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch("/api/posts")
.then((res) => res.json())
.then(setPosts);
}, []);
return posts;
}
Data-fetching libraries
For larger apps, use:
- React Query (TanStack Query)
- SWR
These help with caching, refetching, loading/error states, and retries.
Important considerations
1) API keys
- Never expose private CMS keys in client-side React code.
- Use public read-only tokens if the CMS supports them.
- For sensitive operations, use a backend or serverless function.
2) CORS
Your CMS API must allow requests from your frontend domain.
3) Images and rich text
- Many CMSs return image URLs and structured rich text.
- You may need special renderers for rich text content.
4) Static vs dynamic rendering
If using Next.js or another SSR/SSG framework:
- fetch content at build time for static pages
- or on the server for SEO and performance
Example with Next.js
If you use Next.js, you can fetch from the CMS on the server:
export async function getStaticProps() {
const res = await fetch("https://api.example-cms.com/posts");
const posts = await res.json();
return {
props: { posts },
revalidate: 60,
};
}
export default function Home({ posts }) {
return (
<div>
{posts.map((post) => (
<h2 key={post.id}>{post.title}</h2>
))}
</div>
);
}
Recommended approach
For most React apps:
- use a headless CMS for content management
- fetch content with TanStack Query or SWR
- use Next.js if SEO or pre-rendering matters
If you want, I can also show:
- a complete React + CMS example
- a Next.js + headless CMS setup
- examples for a specific CMS like Contentful, Sanity, or Strapi