loading...

Using React hooks in MDX

sebastienlorber profile image Sebastien Lorber Updated on ・1 min read

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?

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.

Posted on by:

sebastienlorber profile

Sebastien Lorber

@sebastienlorber

I help startups be highly productive with React

Discussion

pic
Editor guide