2

When creating an app using create-react-app I get the following error when trying to use hydrate instead of the default .render. Here is the src/index.js file's contents.

import React from 'react';
import ReactDOMServer from 'react-dom/client';
import './index.css';
import App from './App';

const root = ReactDOMServer.createRoot(document.getElementById('root'));
root.hydrate(
 <React.StrictMode>
   <App />
 </React.StrictMode>
);

Running the above code npm start produces the following error

Uncaught TypeError: root.hydrate is not a function

The error is not present if I change the .hydrate back to .render and I am not sure why this is happening.

tpmccallum
  • 41
  • 3

2 Answers2

2

hydrate has been replaced with hydrateRoot in React 18.

hydrateRoot(container, element[, options])

You can check for more info about hydrateRoot here : Documentation

// Before React 18
import { hydrate } from 'react-dom';
const container = document.getElementById('app');
hydrate(<App tab="home" />, container);

// After React 18+
import { hydrateRoot } from 'react-dom/client';
const container = document.getElementById('app');
const root = hydrateRoot(container, <App tab="home" />);
// Unlike with createRoot, you don't need a separate root.render() call here.
PR7
  • 1,524
  • 1
  • 13
  • 24
  • Thanks so much @PR7, I responded in the form of an "answer" because it did not seem possible to show my code blocks in one of these comment boxes (which have limited characters also). Your solution worked perfectly and the link to the documentation was very handy and much appreciated. Kind regards Tim (tpmccallum) – tpmccallum May 22 '22 at 23:32
  • @tpmccallum Happy to help. Good luck with your project :) – PR7 May 23 '22 at 00:21
2

Thank you @PR7 that worked perfectly.

Please note, as my original file syntax was slightly different (from your example), I have written my "before" and "after" below; in case it can help anyone else.

// Before
import ReactDOM from 'react-dom/client';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.hydrate(
  <React.StrictMode>
   <App />
 </React.StrictMode>
);

// After

import { hydrateRoot } from 'react-dom/client';
const container = document.getElementById('root');
const root = hydrateRoot(container, <App />);
tpmccallum
  • 41
  • 3