react-single-instance
v0.1.2
Published
Render a component at most once for a given id, app-wide - safely absorbs React.StrictMode's dev double-invoke
Downloads
430
Maintainers
Readme
react-single-instance
Render something at most once for a given id, app-wide - a component, a hook, and a HOC, all sharing one registry. Useful for a modal root, a toast host, or any other element that must exist exactly once even if it gets mounted from more than one place by mistake.
| | first claimant | every claimant after it |
| --- | --- | --- |
| <SingleInstance id="x">children</SingleInstance> | renders children | renders nothing |
| useSingleInstance('x') | returns true | returns false |
| withSingleInstance(Component, 'x') | renders <Component /> | renders nothing |
npm i react-single-instanceimport { SingleInstance, useSingleInstance, withSingleInstance } from 'react-single-instance';<SingleInstance>
<SingleInstance id="modal-root">
<ModalHost />
</SingleInstance>If a second <SingleInstance id="modal-root"> mounts anywhere else in the tree, it renders nothing.
useSingleInstance
function ModalHost() {
const granted = useSingleInstance('modal-root');
return granted ? <div className="modal-host" /> : null;
}withSingleInstance
const GuardedModalHost = withSingleInstance(ModalHost, 'modal-root');initSingleInstance()
Not required — claims release automatically when their component unmounts. Kept for compatibility with earlier versions, and as a manual way to reset the registry (e.g. in tests).
Playground
An interactive demo of all three APIs side by side, with the source for each shown right next to it:
npm run playgroundClick "mount another claimant" to watch new attempts get rejected live, "re-render" to confirm a granted instance never loses its slot, and "unmount" to see that removing a claimant frees its id for the next one.
Development
npm install
npm run build # tsup: ESM + CJS + d.ts
npm test # Vitest (happy-dom)
npm run test:coverage
npm run playground # http://localhost:4174Have a good productive day :)
If you like this package please consider donation Click Here
License
MIT © 2026 Itay Merchav
