How to resolve "TypeError: useOptimistic only works in Client Components" in Next.js with use client directive

167 Views Asked by At

I'm trying to use the useOptimistic hook in my Next.js page, and I've added the "use client" directive at the top of my file as suggested by the error message. However, I'm still encountering the error:

TypeError: useOptimistic only works in Client Components. Add the "use client" directive at the top of the file to use it.

Here's a snippet of my code:

"use client";

import { useEffect, useState } from "react";
import Header from "../components/Header";
import { useOptimistic } from "react";

function Categories() {
  const [categories, setCategories] = useState([]);
  const [optimisticCategories, addOptimisticCategory] = useOptimistic(
    categories,
    (state, newCategory: string) => [...state, { category: newCategory }]
  );

  useEffect(() => {
    const fetchData = async () => {
      const res = await fetch("/api/categories");
      const data = await res.json();
      setCategories(data);
    };

    fetchData();
  }, []);

  return (
    <main className="m-8">
      <Header />
    </main>
  );
}

export default Categories;

"next": "^13.5.4"

I've read the documentation on Next.js, but I'm still facing this issue. Any insights on how to resolve this error would be greatly appreciated. Thanks!

1

There are 1 best solutions below

0
On

I found out that useOptimistic works only with App router and I tried to use it with the old Page router.