Sobes.tech
Middle

How does the state behave if a component is rendered through a portal elsewhere in the DOM?

sobes.tech AI

Answer from AI

In React, a component's state is stored within the component itself, regardless of where it is rendered in the DOM. When using a portal (ReactDOM.createPortal), the component is visually rendered elsewhere in the DOM tree, but it remains logically in the same place in the React tree where it was declared.

This means that the component's state is not reset and behaves as if the component was rendered in a normal location. The portal only affects the placement in the DOM, not the component's lifecycle or state.

Example:

function Modal() {
  const [count, setCount] = React.useState(0);
  return ReactDOM.createPortal(
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>,
    document.getElementById('modal-root')
  );
}

Here, the count state is preserved, even though the content is rendered in modal-root outside the main DOM node of the application.