-
-
Notifications
You must be signed in to change notification settings - Fork 191
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
Differences between computed
and a hook
#782
Comments
Another question: The documentation says that computed values might not be up-to-date when accessed from actions. Is this also true when the values are accessed from thunks? |
Hi @KevinMusgrave !
In your specific example, the difference is nothing - other than using store state directly (via the hook) or using a computed property. However, there is a caveat to
I am not 100% certain, but I would assume this is also the case for Hope that answers your questions 😄 |
Thanks for the fast reply! I guess one advantage of This brings me to a broader question: what is the best way to re-use complex logic within actions and thunks, without the caching limitation of For example: function useComplicatedValue(id){
const x = useStoreState(state => state.a.foo[id])
const y = useStoreState(state => state.b.bar[x])
return useStoreState(state => state.c.baz[y])
} This is a hook, so it can't be used inside actions and thunks. On the other hand, if I make it a Is there another approach? |
Well it might be in some cases - and it all depends on your store. I would suggest you to test out if computed props are working in your case. If it works - great, if it doesn't, you can get around it via the solution below.
Computed props are just derived of state. If you are worried that you might get cached computed props, you could extrapolate the "compute" generator and reuse it within your action/thunk to regenerate the data based on the current state. const model = {
comptutedProp: computed((state) => generateComplexData(state))
myAction: action((state) => {
const data = generateComplexData(state)
// etc..
})
}
const generateComplexData = (state) => { /* extract from state */ } |
Ok that seems like a reasonable approach. I'm also wondering about re-renders using How does it determine if the input state has changed? If the input state is an object, will the input always be considered "changed" and cause excessive re-renders? I'm able to pass a custom equality function to |
The input is deep-diffed based on the previous previous input. The computed property is also checked and only updated if it has changed, to prevent excessive renders. see #764 for more details
State resolvers provides the input to the computed props. Equality checks are handled internally. Read about state resolvers for computed props here. |
What are the differences between using
computed
:And a hook like this:
The text was updated successfully, but these errors were encountered: