title: React Reverse Portals published: true description: New React library to help with performance & simpler state management tags: react, javascript, webdev, showdev


Hey Dev.to!

I've just built a new library for React: https://github.com/httptoolkit/react-reverse-portal

It lets you define, mount & render a component once, in one place, and then place it in the React & DOM tree somewhere totally different, move it up/down/around the tree later, or even pull it out of the page entirely and put it back, all without remounting or necessarily rerendering.

It's similar to the built-in React portals (and it uses them internally), but effectively the opposite. Instead of defining some content within your tree and pushing it elsewhere via raw DOM, you define your content elsewhere and then pull it into the React tree where you want it to appear.

No DOM work required: just get a node, place an InPortal somewhere with your content & the node, and an OutPortal elsewhere with the node, and your content is magically sent from one to the other.

Useful if you want to avoid unnecessary recreation of components. That lets you avoid losing react state or DOM state (e.g. playing video elements), avoid recreating expensive-to-initialize components, and generally separate here your component is define from where it's used.

There's an example in the readme and a storybook of live examples too.

Let me know what you think!