In an application, we don’t always need a whole state, sometimes we just need a piece of that information, or we need to combine multiple states into one. That’s where Computed fits in!
Every time the user state changes, this Computed callback is re-executed and if the resulting value is different, it will then notify the components watching it.
In the last example, everytime the cart or the product map changes, the Computed callback is re-executed automatically, and it’s only when the total price changes between two executions, that the components that are interested in this value, are notified.
Computed with Parameter
Let’s say you have a widget which has a productId parameter and you want to get the product with this id.
Since we must not create a Computed inside a build method, how can we get a Computed which depends on productId?
One way to do it, is to have a specific Provided for the current product id and to override it in a StateStore:
As you can see, this is pretty cumbersome.
Another way would be to safely generate a Computed on the fly, with a parameter. And this is possible:
This is far more easier and it’s safe because the generated Computed can be tracked and disposed properly when it’s not longer in used.