Skip to content

feat(atoms): dynamically update atom exports; improve export wrapping #256

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

bowheart
Copy link
Collaborator

@bowheart bowheart commented May 22, 2025

Description

Since the inception of atom exports, they've always had the requirement of being "stable". When creating an exported function, you have to ensure the function doesn't close over any values that can become stale. This is because Zedux only sets the atom's exports after initial atom evaluation and never updates them.

Zedux does that because working with stable exports is much easier than trying to figure out when those exported function references change out from under you. Exports are not state, so there's no easy way to tell when the reference is updated. Basically, that would mean you should never destructure the exports off an atom:

const { someExport } = useAtomInstance(myAtom).exports

useEffect(() => {
  // if exports weren't stable, `someExport` may be outdated here
}, [])

Turning all exports into a JS Proxy wouldn't improve this DX either. But there is something we can do. Since atom apis already wrap functions by default, we can swap out the underlying function that Zedux's function wrapper wraps. This fixes the by-far most common scenario of an exported function closing over a stale value by allowing those exported function references to change while keeping the exposed function references stable for consumers.

Implement this dynamic wrapping. Also improve the wrapping logic's function detection to exclude classes themselves or any functions with static properties attached. All non-normal function values are still never updated after initial evaluation. And that's fine - any non-function values that are expected to update should be put in state (or the atom's promise).

TL;DR You can now do this:

const exampleAtom = atom('example', () => {
  const signal = injectSignal('some state')
  const state = signal.get()

  const someExport = () => state // totally fine now!

  return api(signal).setExports({ someExport })
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant