John Otander

React Hooks in MDX

MDX is frequently used to embed components that are dynamic, it’s one of its key features. It’s my favorite part, particularly for educational posts on complex topics.

You can make things interactive.

But, you can do more, too.

Sometimes I don’t need, or want, to create separate components for small things that will never be used outside of a particular MDX file. This can include something interactive or related to data. You can achieve this inside your MDX file with React hooks.

import { useState } from 'react'

# Here's a button, click it!

export const MyDynamicButton = () => {
  const [count, setCount] = useState(0)
  return (
    <button onClick={() => setCount(count + 1)}>Clicked {count} times!</button>
  )
}

Click it! <MyDynamicButton />

Note: It’s important that you don’t include any empty lines in the code block since there’s currently a parsing bug that will hopefully be addressed in v2.

That’s it. Here’s the exact code in the code block copied over into the very MDX file I wrote this post with:

Click it!


Sign up for my newsletter

If you want early access to what I'm researching, writing, and building, you should subscribe to my newsletter.

No spam, ever. You can unsubscribe at any time.