valtio-select - utility for structural changes and nullable proxies
#1171
paol-imi
started this conversation in
Show and tell
Replies: 2 comments
|
Very nice! I'll definitely take a look. |
0 replies
|
I like the impl style that depends only on public api. |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Hey Valtio community,
First, a big thank you to the maintainers and everyone here. The library is excellent, and the existing discussions and resources have been incredibly helpful for learning and building with it.
While working on a project, I ran into a couple of common scenarios where
useSnapshotcan be tricky:nullorundefinedtouseSnapshot(e.g.,useSnapshot(state.user)whenuserisnull) throws an error.useSnapshot(state.user)) doesn't update the component if theuserobject itself is later replaced with a new one.To address these points, I created a small companion library,
valtio-select. It introduces a single hook,useTrackedSnapshot, which uses a selector function to create smarter subscriptions that automatically adapt to these cases.Here is a quick example that solves both problems at once:
The hook works by tracking exactly which properties are accessed in the selector. If any of them change, it re-runs the tracking and rebuilds the subscriptions, so it never has stale references.
It also provides:
subscribeTrackedfunction.There are surely multiple possible solutions to these challenges, but I aimed for an approach that felt simple, effective, and true to the minimal spirit of Valtio. A key goal was to ensure it's fully compatible with any existing codebase, allowing you to adopt it for specific components without needing to change your state structure or anything else.
I built this to hopefully give back a little to the ecosystem and would love any feedback. You can find the library here:
Repo Link: https://github.com/ts-zen/valtio-select
All reactions