Skip to main content

useEcosystem

import { useEcosystem } from '@zedux/react'

A React hook that returns a reference to the nearest ecosystem that's been provided over React context via <EcosystemProvider>. If no ecosystem has been provided, Zedux will return the global ecosystem. If the global ecosystem hasn't been created yet, Zedux will create it.

The ecosystems walkthrough details when Zedux uses which ecosystem.

Examples

Live Sandbox
12345678910111213141516171819
const secondsAtom = atom('seconds', () => {
const store = injectStore(0)

injectEffect(() => {
const intervalId = setInterval(() => store.setState(val => val + 1), 1000)

return () => clearInterval(intervalId)
}, [])

return store
})

function Seconds() {
const ecosystem = useEcosystem()
const instance = ecosystem.getInstance(secondsAtom)
const state = useAtomValue(instance)

return <div>Seconds: {state}</div>
}
Live Sandbox
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
const secondsAtom = atom('seconds', (startingNumber: number) => {
const store = injectStore(startingNumber)

injectEffect(() => {
const intervalId = setInterval(() => store.setState(val => val + 1), 1000)

return () => clearInterval(intervalId)
}, [])

return store
})

function First() {
const seconds = useAtomValue(secondsAtom, [0])

return <div>First State: {seconds}</div>
}

function Second() {
const seconds = useAtomValue(secondsAtom, [10])

return <div>Second State: {seconds}</div>
}

function App() {
const [isStarted, setIsStarted] = useState(false)
const [isFirst, setIsFirst] = useState(true)
const ecosystem = useEcosystem()

const start = () => {
setIsStarted(true)

// preload both counters, so they start at the same time:
ecosystem.getInstance(secondsAtom, [0])
ecosystem.getInstance(secondsAtom, [10])
}

return (
<>
{!isStarted ? (
<button onClick={start}>Start Counting!</button>
) : (
<>
{isFirst ? <First /> : <Second />}
<button onClick={() => setIsFirst(val => !val)}>Toggle View</button>
</>
)}
</>
)
}

Global and custom ecosystems:

function Child() {
const ecosystem = useEcosystem() // { id: 'root', ... }
...
}

function App() {
const ecosystem = useEcosystem() // { id: '@@global' ... }

return (
<EcosystemProvider id="root">
<Child />
</EcosystemProvider>
)
}

Signature

useEcosystem = () => ecosystem
Returns

An ecosystem object.

This is the global ecosystem if no ecosystem has been provided above this component via an <EcosystemProvider>. If an ecosystem has been provided, this is a reference to that ecosystem.

See Also