tpmccallum
tpmccallum

Reputation: 61

Why do ReactDOMServer and ReactDOM give the "root.hydrate is not a function" error

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.

Upvotes: 3

Views: 2592

Answers (2)

tpmccallum
tpmccallum

Reputation: 61

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 />);

Upvotes: 3

PR7
PR7

Reputation: 1914

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.

Upvotes: 3

Related Questions