reactjsreact-portal

Why is the React portal a state?


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.


Solution

  • 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.