I am learning React and I have a question. Sometimes we use the previous State when we want to set a new value:
import React, { useState } from "react";
function HookCounter() {
const initialCount = 0;
const [count, setCount] = useState(initialCount);
return (
<div>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount((prevState) => prevState + 1)}>
Increment
</button>
<button onClick={() => setCount((prevState) => prevState - 1)}>
Decrement
</button>
</div>
);
}
export default HookCounter;
This is because we are building the new state on top of the previous state.
Does that mean that if we use the spread
operator (for example in an array or an object), we don't need to use the previous State? Because spread
gives us the previous State already?
For example
import React, { useState } from "react";
function ArrayCounter() {
const [items, setItems] = useState([]);
const addItem = () => {
setItems([
...items,
{
id: items.length,
value: Math.floor(Math.random() * 10) + 1,
},
]);
};
return (
<div>
<button onClick={addItem}>Add a number</button>
<ul>
{items.map((item) => (
<li key={item.id}>{item.value}</li>
))}
</ul>
</div>
);
}
export default ArrayCounter;
Thank you!