Reputation: 274
I'm trying to learn how to implement a list in react. The docs recommend that I use the hooks API to use state. I read through them, and I have an idea of how to implement one:
function ListReducer(list, action) {
switch(action.type) {
case 'push': {
listCopy = [...list]
listCopy.push(action.data);
return listCopy
}
}
}
const [state, dispatch] = useReducer(ListReducer, []);
However, this strikes me as very inefficient, since the entire list needs to be copied in order to return the value, and generally this only takes O(1). Is there a better way to handle this situation?
Upvotes: 0
Views: 92
Reputation: 2985
that's the nature of using the state/reducer pattern, nothing out of the box in the JavaScript language to change/handle that...
there's a library called immer
, the basic idea is that with Immer you will apply all your changes to a temporary draft, which is a proxy of the currentState. Once all your mutations are completed, Immer will produce the nextState based on the mutations to the draft state,
turning your code in:
import produce from "immer"
function ListReducer(list, action) {
switch(action.type) {
case 'push': {
let nextState = produce(list, draftState => {
draftState.push(action.data)
})
return nextState
}
}
}
const [state, dispatch] = useReducer(ListReducer, [])
when using immer, there's a significant reduction in the maintenance for your team on "are we using mutable/immutable APIs in JavaScript?"... with immer, you remove this problem
Upvotes: 1
Reputation: 370679
Since you're using React, there is no way to change the state of an array without iterating over the entire array - you can't, for example, just .push
to the existing array, because that'd mutate the state.
There is no definitively better option than your general approach - but you can make the syntax look a bit nicer:
case 'push':
return [...list, action.data];
The efficiency of a given section of code rarely matters in real-world projects, usually. There are often one or a few sections of code that are bottlenecks, but the likelyhood that any given section you're looking at at the moment is the bottleneck is slim.
Don't worry about it until you see that your app is running slower than desirable, and when that happens, run a performance analysis to see what exactly the bottleneck is, and fix that - until then, it's often not worth taking the time to worry about.
Upvotes: 2