-
I'm referring to this example: // from the docs
const useStore = create((set, get) => ({
sound: "grunt",
action: () => {
const sound = get().sound
// ...
}
}) In our specific use case we use something like this (very much simplified): // store.js
const useStore = create((set, get) => ({
products: [],
getProductCount: () => get().products.length,
}) In our component we use the hook like so: // Component.jsx
import useStore from './store'
export default Component = () => {
const getProductCount = useStore((state) => state.getProductCount)
return <div>{getProductCount()}</div>
} Now the problem is that since the function reference doesn't change, there will be no rerender of the component and therefore the function will return a stale value. One "workaround" we found is this one, but we find it to be very ugly. Also now it rerenders on every state change, which is the other extreme // Component.jsx
import useStore from './store'
export default Component = () => {
const getProductCount = useStore(
(state) => state.getProductCount,
() => false // custom compare function
)
// might as well use this:
// const { getProductCount } = useStore()
// this also triggers a rerender on ANY state change
return <div>{getProductCount()}</div>
} I know this rather a feature than a bug but I wonder how the inteded usage looks like with these functions.Another question, would you consider something like this to be best practice: // ...
const productCount = useStore((state) => state.products.length)
// ^^^^^^^
// talking about this
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Yes! |
Beta Was this translation helpful? Give feedback.
Yes!