Writing impure reducers? #697
Replies: 2 comments 1 reply
-
That may seem to work in zustand, because it merges states.
Are you sure if it's a huge operation? Do you have thousands of properties? meaning |
Beta Was this translation helpful? Give feedback.
-
Hey @dai-shi, thanks so much for the reply. That was a pretty contrived example. Our application is a document editor where we have an array of sections, and each section has an array of blocks. So when we update something as simple as the block name, we have to map over all the sections, find the matching section, then map over the section's blocks and find the matching block, and update that block. export const updateBlock = (state, action, updateFn) => {
return {
...state,
hasChanges: true,
data: {
...state.data,
sections: state.data.sections.map((section, sectionIndex) => {
if (sectionIndex === state.sectionIndex) {
return {
...section,
blocks: section.blocks.map((block) => {
if (
block.id === action.blockId ||
block.id === action.block?.id
) {
return updateFn(block)
}
return block
}),
}
}
return section
}),
},
}
} Could we alternatively write it as follows: export const updateBlock = (state, action, updateFn) => {
let block = state.data.sections[state.sectionIndex].blocks[action.blockIndex]
state.data.sections[state.sectionIndex].blocks[action.blockIndex] =updateFn(block)
state.hasChanges = true
return state
} Thanks again |
Beta Was this translation helpful? Give feedback.
-
Hello!
We are adding zustand to our application to replace our use of React.useReducer.
One thing that bugs me about useReducer is it expects the reducers to always be pure even if super inefficient.
example:
That spread of state could be a huge operation if state is huge.
What I'm finding from initial tests is that I can just do
I'm not running into any issues with this, am I missing something?
Beta Was this translation helpful? Give feedback.
All reactions