React has different ways we could manage our state. One of them is useState
. useState
is the simplest and easiest-to-understand way to manage state.
useState
accepts an initial state which could be a string, number, object, array, etc. It then returns an array consisting of the state and a setter.
const [counter, setCounter] = useState(0)
The setter returned is used to update the value of the state. The setter can accept the new value or a function. The function passed to the setter receives the previous state as its argument.
setCounter(1)
setCounter(previousState => previousState + 1)
It's important to note that whatever the setter receives as a value or is returned by the function will full replace what's inside of the state.
const [books, setBooks] = useState([])
setBooks({ title: New Book })
console.log(books) // { title: New Book }
setBooks(previousState => [
...previousState,
{ title: New Book }
])
console.log(books) // [{ title: New Book }]
Here's couple of solutions to common problems that seem to come up frequently with beginners.
Add to Array
const [books, setBooks] = useState([])
const addBook = (newBook) => {
setBooks(previousState => [
...previousState,
newBook
])
}
Remove from Array
const [books, setBooks] = useState([])
const removeBook = (index) => {
setBooks((previousState) => {
const booksCopy = [...previousState]
return booksCopy.slice(index, index + 1)
}
}
Update item in Array
const [books, setBooks] = useState([])
const updateBook = (index, newBook) => {
setBooks((previousState) => {
const booksCopy = [...previousState]
booksCopy[index] = {
...booksCopy[index],
...newBook
}
return booksCopy
}
}
Top comments (1)
I've been working on react for about 9 months now but I keep reading these articles. Simplicity is the key to convey message in a good way. Loved it.