How to avoid triggering tracking when I reshape snapshots in custom hook? #835
-
Hi there, I am building a custom hook that needs to reshape snapshots from global state. For example: const state = proxy({
fieldA: {
data: 'abc',
createdAt: 'sometime',
owner: 'someone'
}
})
function useFieldData(name) {
const snap = useSnapshot(state)
const field = snap[name]
return {
data: field.data,
metadata: {
createdAt: field.createdAt,
owner: field.owner
}
}
} As above, both of It isn't expected for me. Because in most cases not every attribute will be used for rendering. I hope components can only react to attributes that they really used. How can I achieve this goal? Is there a way I can disable access tracking temporarily in my hook and enable it again when returns? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
It's better to use
Unfortunately not. It's always on or always off. See: |
Beta Was this translation helpful? Give feedback.
-
If you want to hide the implementation detail, another solution is to make the hook more explicit. function useFieldData(name, name) {
const snap = useSnapshot(state)
const field = snap[name]
return field
} |
Beta Was this translation helpful? Give feedback.
Because valtio is the implementation detail in my hook, I don't like to expose it to consumers.
I think there should be one solution is I can get raw snapshot from
snapshot(state)
api for constructing my returns, then wrap them with proxy and maintain subscriptions by myself just like whatuseSnapshot
did. But I'm not sure how complex it will be.