Understanding Hydration Errors by Building a SSR React Project

(propelauth.com)

22 points | by aisrael 3 days ago ago

6 comments

  • Etheryte a day ago

    Can't help but feel that all the approaches avoiding the error by using delayed state are missing the forest for the trees. The error tells you that the client and the server disagreed on what the output is. If the client has different data, for example due to local storage, that's the expected behavior! Don't mangle your code with weird workarounds for something that isn't broken. Similar to all other rules, it's important to know when the rule should be broken.

    • kevincox 15 hours ago

      The problem is that React's handing of this isn't good if the initial render isn't a match. At the very least it will mess up form fields including browser-saved values. It can also be very expensive.

      So even though the client has and wants a different value the correct thing to do according to the React framework is to ensure that the first render perfectly matches the server so that the React state matches the DOM, then immediately re-render with the desired client state. This will be faster (the DOM changes will be minimized rather than completely deleted and recreated) and more correct (preserving DOM state and browser functionality).

      In theory React could read the DOM and do a proper diff and make this de-sync less harmful. But this is probably still less efficient then doing a small amount of work to make the first render match (which is basically just building up the virtual DOM to match the real DOM).

    • zackify a day ago

      Completely agree. Surprised it has to many upvotes when it ends with a “fix” telling you to make useStates that rely on localstorage when you’re doing SSR

  • a day ago
    [deleted]
  • edzzde 18 hours ago

    > One reason you may care about hydration errors is because it’s an awkward user experience.

    I don't know.. A hydration error is 100% an application logic error. It's not some "slightly worse UX". It means you are actually doing something incorrectly. I would even compare it to C++ UB.

    • kevincox 15 hours ago

      It's not at all comparable to C++ UB as React says what will happen in this case. But what React does is slow and has bad UX.