2

I am trying to implement a Redux in a simple React application that uses the latest version (React 18). Here is my code in index.js so far:

import React from 'react';
import ReactDOM from 'react-dom/client';
import { store, App } from './App';
import { createStore } from 'redux'

export const renderApp = () => {
    ReactDOM.createRoot(document.getElementById('root')).render(<App />);
}

renderApp()

store.subscribe(renderApp)

However, I get a warning in the console that says:

"You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before. Instead, call root.render() on the existing root instead if you want to update it"

What is the supposed to mean, and how would I need to change my code in index.js?

WannaInternet
  • 327
  • 1
  • 6
  • 14
  • 1
    you're calling `renderApp` and also passing it to `subscribe` which will call it again. The error is very descriptive, only createRoot once and then reuse the returned root. You should instead be passing a callback to subscribe which uses the already created root. – pilchard May 31 '22 at 00:03
  • Simply remove `renderApp()` from your code. You're calling it manually, and then the subscriber is also doing it. – code May 31 '22 at 00:07
  • 3
    @code the subscription will call the passed callback repeatedly, so the callback should be using an already initialized root. – pilchard May 31 '22 at 00:08
  • @code- if I remove the renderApp() line then my component doesn't even render in the first place – WannaInternet May 31 '22 at 00:12
  • See also [React-18 | You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before](https://stackoverflow.com/questions/71792005/react-18-you-are-calling-reactdomclient-createroot-on-a-container-that-has-a/75052925#75052925) – ggorlen Jan 11 '23 at 04:48

1 Answers1

1

The most basic implementation would be something like the following, which creates a single root, renders against it, and then passes a callback which closes over that root for further subscription calls.

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

store.subscribe(() => root.render(<App />));
pilchard
  • 12,414
  • 5
  • 11
  • 23