mdx-js / mdx

Markdown for the component era
https://mdxjs.com
MIT License
17.72k stars 1.14k forks source link

Can a mdx document include hooks? #1087

Closed kuworking closed 4 years ago

kuworking commented 4 years ago

My use case, transform this to its useRef version

export const scrolling = ref => indexRefs[ref].current.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' })
export const indexRefs = Array(15).fill(0).map(() => createRef())
// export const indexRefs = useRef([14]) // hooks cannot be run within a useEffect
johno commented 4 years ago

You should be able to use hooks assuming they're wrapped up in an inline component. Here's a post I wrote a little while which hasn't been added to the docs quite yet: https://johno.com/react-hooks-in-mdx/

kuworking commented 4 years ago

Thanks! I see that you have to encapsulate it within a function, which makes it difficult to have a global const that stores the useRef and then have another function that can have access to this variable

Any solution that I can think of adds more code than the two lines I've written before, maybe there's something I'm not considering here (?)

Is the fact that hooks cannot be executed without being wrapped something made by design or just something to be implemented in the future?

johno commented 4 years ago

Thanks! I see that you have to encapsulate it within a function, which makes it difficult to have a global const that stores the useRef and then have another function that can have access to this variable

Not 100% sure what you're trying to do, but I think you can achieve something similar by using a custom provider and using context.

Is the fact that hooks cannot be executed without being wrapped something made by design or just something to be implemented in the future?

Hooks are more of a library implementation detail which we don't intend on exposing because we only parse JSX and import/exports. Though, in the future (after v2 ships) support will be possible via plugins.

kuworking commented 4 years ago

Not 100% sure what you're trying to do, but I think you can achieve something similar by using a custom provider and using context.

Yes, that's what I was also thinking, and it looks to me that this means more trouble than just using createRef

Anyway, looking very much forward for v2, thanks for your work :)