Replies: 1 comment 10 replies
-
jotai-scope has this. And we could add an But yes, Zedux can do it using a unique id param (I wouldn't use An early prototype of Zedux had "Local Atoms" that were instantiated every time they were used - you had to share the atom instance reference to avoid creating extra instances. We got rid of them because they:
Anyway, here's how: const settingsAtom = atom('projectSettings', (_id: string) => {
const store = injectStore(hydration => createStore(null, hydration), {
hydrate: true,
})
return store
}, { ttl: 0 }) // <- EDIT: I'd definitely add this
function SettingsProvider({
children,
settings: initialSettings,
}: {
children: ReactNode,
settings: ProjectSettings,
}) {
// initialize a new settingsAtom every time this component mounts
const id = useId()
const ecosystem = useEcosystem()
const settingsInstance = useMemo(() => {
// set up initial state before instantiating:
ecosystem.hydrate({
[settingsAtom.getInstanceId(ecosystem, [id])]: initialSettings,
})
// now create a new instance for this component:
return ecosystem.getInstance(settingsAtom, [id])
}, [ecosystem, id]) // snapshot initialSettings - don't pass as dep
return <AtomProvider instance={settingsInstance}>{children}</AtomProvider>
} |
Beta Was this translation helpful? Give feedback.
10 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
So its quite hard for me to describe, but what i want is very simple, similar like react context.
i just need similar good old
useState(initialValue)
, but the state/setState i can access from any component.I think it related to #127.
i also don't want to use init function, as i am using remix/react-router 7, since it use ssr on first hit, so the data is available immediately on first render. (if i create init function, i need to use
useEffect
to load and re-render from empty to filled which i don't want to).but i can't do it since if zedux atom key is same, it will not trigger
injectStore
again. so i kind of need{ cache: false }
config.i can use random value like
Math.random()
for the second params ofuseAtomInstance
which i think it will works as i intended, but it obviously not the best way since i will end up in many unused instances.is this possible on zedux? @bowheart
i think it's more similar with jotai atom of what i want to achieve, since they don't use key? i haven't try jotai again.
Consume
React context equivalent. works as intended, but suffer from frequent update like slider update value.
Beta Was this translation helpful? Give feedback.
All reactions