Maaz Mustafa
Maaz Mustafa

Reputation: 21

Warning: Invalid hook call. Hooks can only be called inside of the body of a function component when MDXRemote execute

I am using nextjs and next-mdx-remote for blogging static websites.

/src/app/blog/post/post1

import dynamic from 'next/dynamic';
import { getPostBySlug } from '@/lib/mdx';
import MDXComponents from '@/components/mdx-components';

const MDXRemote = dynamic(() => import('next-mdx-remote').then(mod => mod.MDXRemote), {
  ssr: false,
});

export default async function BlogPost() {
  const slug = 'post1';
  const { mdxSource, frontMatter } = await getPost(slug);

  if (!mdxSource) {
    return <div>404 - maaz here</div>;
  }

  return (
    <div>
      <h1>{frontMatter.title}</h1>
      <MDXRemote {...mdxSource} components={MDXComponents} />
    </div>
  );
}

Due to this MDXRemote { Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatched versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app } this error occur when I comment out this MDXRemote then this error disappear

while in above code I use getPost this is place at /src/lib/mdx.tsx and this function is below

export const getPost = async (slug: string) => {
  const filePath = path.join(contentDir, `${slug}.mdx`);

  try {
    const source = fs.readFileSync(filePath, 'utf8');
    const { content, data } = matter(source);
    const mdxSource = await serialize(content);
    return { mdxSource, frontMatter: data };
  } catch (error) {
    console.error('Error reading file:', error);
    return { mdxSource: null, frontMatter: null };
  }
};

So, kindly tell me what is the main reason for above error. I tried to solve this using many methods using getStaticProps() but nextjs 13 version is not applicable in /app dir so this also gives error

I am trying to convert mdx file into react component and use it in my site using serialize and MDXRemote but this error occur Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatched versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem. ⨯ Internal error: TypeError: Cannot read properties of null (reading 'useState')

Upvotes: 2

Views: 171

Answers (1)

Sakar
Sakar

Reputation: 567

You are using the app directory which does not need serialize and should be imported from next-mdx-remote/rsc take a look at the section titled "React Server Components (RSC) & Next.js app Directory Support" in their documentation

Upvotes: 1

Related Questions