I am working on my project and i noticed that when strict mode is turned on it pushes two identical elements into my array. When the strict mode is off it pushes only one element into the array. Is there any explanation why this happens?
import {getRandomNumber} from './utils';
export function registerTicket() {
const newTicket = {
number: getRandomNumber(),
color: 'red',
}
this.setState((prevState) => {
prevState.tickets.push(newTicket);
return {
remainingTickets: --prevState.remainingTickets,
tickets: prevState.tickets,
}
})
}
Here is my state.
this.state = {
winningNumber: getRandomNumber(),
remainingTickets: 5,
tickets: [],
finished: false
};
React StrictMode
helps expose unintentional side-effects by intentionally double-invoking certain lifecycle methods and React hooks. The setState
updater function is one that is called twice. I'll leave the in-depth explanation to the linked questions.
Detecting unexpected side-effects
Your unintentional side-effect is a state mutation of the previous tickets
state when you push a new element into it and when you pre-decrement the remainingTickets
state. The hat-trick is that you also don't return a new tickets
array referece.
this.setState((prevState) => {
prevState.tickets.push(newTicket); // <-- mutation!!
return {
remainingTickets: --prevState.remainingTickets, // <-- mutation!!
tickets: prevState.tickets, // <-- same old array reference
}
})
The solution is to shallow copy the previous state array into a new array reference and append the new element.
this.setState((prevState) => ({
remainingTickets: prevState.remainingTickets - 1,
tickets: [...prevState.tickets, newTicket],
}));