Zustand causing more rerenders than expected #2642
-
Hello 👋 I am trying to convince my team (and myself) that is is worth for us to switch from using React Context as state management to Zustand. To better illustrate the value gained, I made a code sandbox with a simple component that uses either as their state management. The component hosts
Each store has two variables, a number and a string. The string variable is never updated, so I did not expect the component that listens to that part of the state to be updated when the count updates - but it does. This is one of the key value propositions of Zustand over React context. I'm new to Zustand, and I can't seem to figure out what I'm doing wrong. Any help would be much appreciated 😄 https://codesandbox.io/p/devbox/react-context-vs-zustand-85h59c |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
@jhalborg you should use const ShouldNotUpdate: FC = () => {
const variable1 = useMyStore(useShallow((state) => state.variable1));
return <div style={{ backgroundColor: 'brown' }}>
<h3>This should NOT update when using Zustand!? {variable1}</h3>
<RerenderCounter />
</div>
} |
Beta Was this translation helpful? Give feedback.
@jhalborg I found the issue you are updating the parent so that trigger new renders on children. You can try using
memo
onShouldNotUpdate