DEV Community

Sebastien Lorber
Sebastien Lorber

Posted on • Updated on


Using React hooks in MDX

Hey, I don't know who needs to read this, but we can use all the power of React and hooks directly in MDX.

You don't necessarily need to create a separate component in a separate file.

Using named exports on MDX makes the React component available to use in the MDX scope.

# Hey

This is an inline counter directly created in MDX:

import React from "react"

export const initialCounterState = 4;

export const MyCounter = () => {
  const [counter, setCounter] = React.useState(initialCounterState);
  return (
    <button onClick={() => setCounter((c) => c + 1)}>
      Increment {counter}

<MyCounter />

That's cool isn't it?
Enter fullscreen mode Exit fullscreen mode

And it would render correctly.

Alt Text

However, with great power comes great responsibility.

I'll let you decide if it's a good idea to do this :)

Follow me on Twitter for updates like this.

Top comments (0)