Skip to content

Error: Cannot read properties of null (reading 'useState') when using useState in my mdx #242

@NinnjA254

Description

@NinnjA254
  • mdx-bundler version: v10.1.1
  • node version: v23.4.0
  • npm version: v10.9.2
  • nextJs version: v15.3.3 (app router)

Relevant code or config

//bundling the Mdx
const result = await bundleMDX({
    source: mdxSource,
    files: {
        './components.tsx': components
    }
})
//rendering the mdx component
"use client"
...
const Component = React.useMemo(() => getMDXComponent(code), [code])
....
return (
  <main>
    <Component components={{ // these custom components don't use react
      a: MyLink,
      pre: Pre,
    }} />
  </main>
)
...
<!-- MdxSource-->
import Foo from './components.tsx'

blah blah normal markdown
<Foo/>
//components
import * as React from 'react'

export default function Foo() {
  const [count, setCount] = React.useState(0)
  
  return (
    <div className='border'>
      <p>{count}</p>
    </div>
  )
}

What you did
I tried to bundle and display my mdx, following the documentation in the README.

What happened
In the dev server, everything works fine, except I get this warning error from next js when I try to useState in my mdx content:
Error: Cannot read properties of null (reading 'useState')
When I build and run npm start
I get a 500 internal server error, with the same message in the terminal:

 ⨯ [TypeError: Cannot read properties of null (reading 'useState')] {
  digest: '<digest code>'
}

Reproduction repository:
https://github.com/NinnjA254/reproduce_mdx_error

Problem description:
I am trying to use mdxBundler in my nextjs app, I followed the guide in the README, but there is a problem rendering mdx that uses the useState hook. The mdx is bundled and rendered in the development server with a warning: Error: Cannot read properties of null (reading 'useState').
After building and npm start, I get 500 internal server error, with this error in the terminal:

 ⨯ [TypeError: Cannot read properties of null (reading 'useState')] {
  digest: '<digest code>'
}

bundling and compiling mdx that doesn't use useState works perfectly fine.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions