modify state by `produce` vs directly

what is the difference between:
const addTodo = (text) => {
setTodos([...todos, { id: ++todoId, text, completed: false }]);
}
const addTodo = (text) => {
setTodos([...todos, { id: ++todoId, text, completed: false }]);
}
and
const addTodo = (text) => {
setTodos(
produce((todos) => {
todos.push({ id: ++todoId, text, completed: false });
})
);
};
const addTodo = (text) => {
setTodos(
produce((todos) => {
todos.push({ id: ++todoId, text, completed: false });
})
);
};
edit:
Immer inspired API for Solid's Store objects that allows for localized mutation.
what's a localized mutation?
4 Replies
thetarnav
thetarnav2y ago
On top level arrays it doesn't change anything I think. But for a nested array, the first one will be a change to the array prop as well—if you have an effect listening to state.myList specifically, it'll get triggered. While doing it with produce will trigger only the "what are all the keys off this list" and "what is the item on the index x" signals Creating a new array possibly also means that all the item signals would need to be recreated for the new array object But those are implementation detail level of differences. I don't think there is a need to use produce for mutating arrays. Doing it the first way works fine, it's easier to write, and this is also what you do with signals. produce is mostly useful when you want to apply many changes to objects on different nesting levels in one go.
Unknown User
Unknown User16mo ago
Message Not Public
Sign In & Join Server To View
thetarnav
thetarnav16mo ago
you could but you need to use batch then produce batches all updates already
Unknown User
Unknown User16mo ago
Message Not Public
Sign In & Join Server To View