Using React hooks in MDX

Sebastien Lorber - Aug 14 '20 - - Dev Community

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}
    </button>
  );
};

<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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .