React Previous State
Published: 2020-02-11 19:51:15

Last week we started the React segment of our program. We learned about State. There are many ways to manipulate State. However, I found the idea of Previous State very convenient. In this post, I will be displaying different ways to utilize previous state.


###State
Before we get into updating and using previous state, let's talk about State first. State is mutable data in a React component. State has the ability to change through its component's life. One example of when to use State is when you might want to increment likes on click.

First you would want to set up the initial state that you will update in a component.

```react
class Like extends Component {

  state = {
   like: 0
  }
}

```

Once you have your initial state declared, you can now use ``setState()`` to update state. ``setState()`` basically just allows you to manipulate state. So we would want our state to update in a way that will increment our likes counter when something is clicked.
```react
class Like extends Component {

  state = {
   like: 0
  }

 handleLikeChange = () => {
   let increment = this.state.like + 1
   this.setState({
    like: increment
    })
 }

render() {
 return(
 <div onClick={this.handleLikeChange}>{this.state.count}</div>
 }
}

```
As the like div is clicked, the like count will go up. In other words state is updating every time that specific div is clicked.

Now that we have an idea of what state is. Let's move on to Previous State!

###Previous State

Remember how we reset the state of the likes count?

```react
 handleLikeChange = () => {
   let increment = this.state.like + 1
   this.setState({
    like: increment
    })
 }

```
You could definitely change state like this or you could use previous state and change it this way:
```react
 handleLikeChange = () => {
   this.setState(prevState => ({
    like: prevState.like + 1 
    }))
 }
```
Both of these work. Previous state just refactors the code without having to declare a variable. The reason we are declaring a variable in the first place is because you cannot call ``this.state`` in ``setState()``. Using previous state allows us to use the previous value of state without having to call state. It keeps track of what state was previously and changes state based on what it was before.

You can update state either way but I found the use of previous state incredibly convenient, especially when multiple set states need to called, since ``setState()`` is asynchronous. 

Here are other ways to utilize previous state:
```react
import React from 'react';
 
class DogToggle extends React.Component {
  constructor() {
    super();
 
    // set initial state
    this.state = {
      isGoodDog: true
    };
  }
 
  // when handleClick is called, setState will update the state so that isGoodDog is reversed
  handleClick = () => {
    this.setState(previousState => {
      return {
        isGoodDog: !previousState.isGoodDog
      }
    })
  }
 
  render() {
    return (
      <div>
        <button onClick={this.handleClick}>{this.state.isGoodDog ? "Good Dog!" : "Bad dog!"}</button>
      </div>
    );
  }
}
 
export default DogToggle;
```
This example creates a toggle button for a good and bad dog. It calls on the status of ``isGoodDog`` and reverses its boolean status to whatever the previous state was. I also found out that you can implement this logic to implement filters on a page. 

```react
import React from 'react';
 
class App extends React.Component {

//set initial state with two empty arrays
    state = {
      storeItemList: [],
      yourWishList: []
    };
  }

//use previous state with a spread operator to call the contents of the ``yourWishList`` array and append the selected item to that array.
selectItems = (selectedItem) => {
  this.setState(prevState => ({
      yourWishList: [...prevState, selectedItem]
  })
}
 
  render() {
    return (
      <div>
       <ItemListContainer items={this.state.storeItemList} 
       onSelectItems={this.selectItems} />
       
       <WishListContainer items={this.state.yourWishList} />
      </div>
    );
  }
}
 
export default App;
```

In this example, I am adding items from one array to another. Two empty arrays are declared in the initial state. To add an item to another array, I need to take a selected item and append it to my desired array. In this case, I declared ``selectedItem`` as a parameter to the ``selectItems`` function. Then I reset state by using a spread operator on previous state. Recall the line ``yourWishList: [...prevState, selectedItem]`` I am reseting the state of yourWishList by taking in all of the previous contents of this array, then appending selectedItem at the end of the contents of the array. 

There are many ways to update state and use previous state. But these are just some of the ways you can update state. Hopefully this helped you understand state and updating state better!