Why is the React portal a state?

848 Views Asked by At

The docs on react portals: https://reactjs.org/docs/portals.html

Like the title asks, I am not really sure why a portal is a state. I am asking about the technicalities about rendering and re-rendering, or if there are some other underlying reasons.

Why should it be in a state, like this:

const [container] = useState(document.createElement('div'));

and not just a regular variable, like this:

const container = document.createElement('div');

EDIT:

When I have the container in a useState() it will update and re-render the content/children without any interruptions. When the container is outside of state, the updates will be choppy.

2

There are 2 best solutions below

0
On BEST ANSWER

Just doing const container = document.createElement('div'); will create a new div each re-render, but by storing it in a state that is unchanged, react will only run that code once and keep hold of that element.

0
On

I have an alternate approach. Instead of adding the createElement calls inside a state variable, I simply moved them out of the react component.

Instead of this

const ModalContainer = (props) => {
  const [modalSection] = useState(document.createElement('section'));
  //do stuff
}

do this

const modalSection = document.createElement('section');

const ModalContainer = (props) => {
 // Do stuff
 // return stuff
}