DEV Community

Karl Castillo
Karl Castillo

Posted on • Edited on

React: useState

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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 }]
Enter fullscreen mode Exit fullscreen mode

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
  ])
}
Enter fullscreen mode Exit fullscreen mode

Remove from Array

const [books, setBooks] = useState([])

const removeBook = (index) => {
  setBooks((previousState) => {
    const booksCopy = [...previousState]
    return booksCopy.slice(index, index + 1)
  }
}
Enter fullscreen mode Exit fullscreen mode

Update item in Array

const [books, setBooks] = useState([])

const updateBook = (index, newBook) => {
  setBooks((previousState) => {
    const booksCopy = [...previousState]

    booksCopy[index] = {
       ...booksCopy[index],
       ...newBook
    }

    return booksCopy
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
monfernape profile image
Usman Khalil

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.