1

I'm currently developing a project with Next.js, and in this project, I'm using the react-markdown library. I've encountered a persistent issue related to re-rendering, and I could use some guidance to resolve this.

The problem is that the react-markdown library keeps re-rendering the component(s) that I have listed in the Options.components object. This happens every time I type something, regardless of where I am typing.

To provide more context, I have attached a video demonstration of the issue I'm facing. In this video, you'll see that whenever I type something, the pre tag re-renders, while other tags such as the p tag do not because I have only customized the code block in the Options.components object.

Pre Tag Re-rendering (Since I cannot post images)

Here's the relevant code snippet where I use ReactMarkdown (I have set reactStrictMode: false for testing):

<ReactMarkdown
  sourcePos
  components={{
    code({ node, inline, className, children, ...props }) {
      const match = /language-(\w+)/.exec(className || "");
      return ...
    },
  }}
>
  {markdown}
</ReactMarkdown>

As shown above, I'm using a code function inside the components prop to customize the code blocks.

I am struggling to find a way to prevent these unnecessary re-renders from happening every time I type. My understanding is that re-rendering should only occur if the specific state or props that the component depends on have changed. Yet, it appears that typing anywhere causes the code component to re-render, which doesn't align with my understanding.

I'd be extremely grateful if anyone could shed some light on this issue. Why are the re-renders happening? How can I modify my code to avoid them? Are there any specific properties or methods in the react-markdown library that I should be aware of?

I tried to debug this problem myself by doing some research and running numerous experiments. I looked into the official documentation of the react-markdown library to see if I could find any methods or properties that might be related to my issue. I've also looked into similar issues. Despite my efforts, I couldn't find any relevant information that could help me understand why this re-rendering issue is occurring.

I expected that typing would only cause a re-render if the specific state or props that the code component depended on were changed. However, it seems that even typing in unrelated areas triggers the re-render, which is perplexing.

Any help would be highly appreciated. Thank you.

Guan-Bo Yang
  • 13
  • 1
  • 4
  • Any update on this? I'm having the exact same issue trying to render a monaco editor inside of a react markdown code block with the chatgpt response streaming set to true. Every delta from the gpt response causing the text to change incrementally, causing markdown to rerender repeatedly – 55 Cancri Aug 23 '23 at 16:06

0 Answers0