gatsbyjs / gatsby

The best React-based framework with performance, scalability and security built in.
https://www.gatsbyjs.com
MIT License
55.28k stars 10.31k forks source link

Hydration failed when using remark plugins in gatsby-plugin-mdx #38089

Open Talaxy009 opened 1 year ago

Talaxy009 commented 1 year ago

Preliminary Checks

Description

Hydration fails when using remark plugins in gatsby-plugin-mdx.

image

I have create a repo which is base on using-mdx example and add a local remark plugin in it to reproduce this issue, you can find the link below. The local remark plugin only does one thing: replace link nodes with html nodes.

Reproduction Link

https://github.com/Talaxy009/gatsby-test

Steps to Reproduce

  1. Clone Reproduction Link
  2. Install dependencies
  3. Run gatsby develop
  4. Visit http://localhost:8000/blog-1/ or http://localhost:8000/blog-2/
  5. Reload the page and you should be able to see the error about hydration

Expected Result

No hydration error.

Actual Result

Hydration error after page reload.

Environment

System:
    OS: Windows 10 10.0.22621
    CPU: (12) x64 AMD Ryzen 5 3600 6-Core Processor              
  Binaries:
    Node: 18.13.0 - ~\AppData\Local\Temp\xfs-dc161e3d\node.CMD
    Yarn: 3.5.0 - ~\AppData\Local\Temp\xfs-dc161e3d\yarn.CMD
    npm: 8.19.3 - D:\Program Files\nodejs\npm.CMD
  Languages:
    Python: 3.10.9
  Browsers:
    Edge: Spartan (44.22621.1702.0), Chromium (113.0.1774.42)
  npmPackages:
    gatsby: next => 5.9.0-next.1 
    gatsby-plugin-mdx: next => 5.9.0-next.0 
    gatsby-plugin-sharp: next => 5.9.0-next.0 
    gatsby-remark-images: next => 7.9.0-next.0 
    gatsby-source-filesystem: next => 5.9.0-next.0

Config Flags

DEV_SSR: true

808vita commented 1 year ago

first of all thanks for the test repo , it helped !

please visit below linked gatsby docs page. https://www.gatsbyjs.com/docs/reference/config-files/gatsby-browser/#replaceHydrateFunction

In the gatsby-browser file add replaceHydrateFunction . To be safe also do a gatsby clean and then build & serve . Tested this on the test repo you provided , it fixed the issues . make sure to import the ReactDOM .

I don't think type:bug is the correct label for this. this existed for quite some time .


import React from "react"
import { Layout } from "./src/components/layout"
import ReactDOM from "react-dom/client";

export const wrapPageElement = ({ element, props }) => {
  return <Layout {...props}>{element}</Layout>
}

export const replaceHydrateFunction = () => {
  return (element, container) => {
    const root = ReactDOM.createRoot(container)
    root.render(element)
  }
}
Talaxy009 commented 1 year ago

@808vita Thanks for your reply. I don't think replacing the react hydrate function is a good way to fix this bug, it's more like hiding it, not to mention that we will lose SSR/SSG functionality in this way. Since this issue has been marked as confirmed, I hope it will be fixed.