I was learning React Hooks and was trying to get how useState works with arrays. So, I have this code:
const App = () => {
const initialTodos = [
{
id: 'a',
task: 'Learn React',
complete: true,
},
{
id: 'b',
task: 'Learn Firebase',
complete: true,
},
{
id: 'c',
task: 'Learn GraphQL',
complete: false,
},
];
const [todos, setTodos] = useState(initialTodos);
const [task, setTask] = useState('');
const handleChangeInput = event => {
setTask(event.target.value);
};
const handleSubmit = event => {
if (task) {
setTodos(todos.concat({ id: 'd', task, complete: false }));
}
setTask('');
event.preventDefault();
};
...
};
The question I wanted to ask is that why do we use concat to immutably add new object into array what if mutate and use push()?