Get() method from store does not force rerender #2358
-
I have a state in zustand where I have a simple get() method to get specific information from my state. What I have noticed however is that in a react component where I call get(), will not rerender upon a state change. Is this an incorrect use of zustand? if so what would be a better approach? I thought of using the state itself, and perform calculations/modifications at the components during render, but that just feels disorganized and repetitive when I need to call this information multiple times throughout my app. Thanks in advance! Here is a snippet illustrating what I mean:
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
@bruno-teruel what about this: const getBearsPlusFive = (bears) => bears + 5
const useBearStore = create()((set, get) => ({
bears: 0,
}))
const BearComponent = (props) => {
const bears = useBearStore((state) => state.bears)
const bearsPlusFive = getBearsPlusFive(bears)
return <p>{bearsPlusFive}</p>
} |
Beta Was this translation helpful? Give feedback.
-
For any future people looking at this, calling the function inside of the selector worked fine. export const useBearStore = create()((set, get) => ({
bears: 0,
getBearsPlusFive: () => {return get().bears + 5}
}) const BearComponent = (props) => {
const bearsPlusFive = useBearStore((state) => state.getBearsPlusFive())
return (<p>{bearsPlusFive}</p>)
} |
Beta Was this translation helpful? Give feedback.
@bruno-teruel what about this: