DEV Community

Gabriel Neto
Gabriel Neto

Posted on • Edited on

How to use prevState of React.useState()

What is "prevState"?

The "prevState" as the name already says (Previous State), get the previous state of your useState hook, this can be used when you have an array in initial state and want to inherit the existing values to add some new values, for example.

How to use?

For this tutorial i created a simple react checkboxes project in CodeSandbox.io to demonstrate, click here to see.

Basically we have a data mock with an array of objects
Image description

After this we have our App component which have a simple useState hook initializing with an empty array

Image description

This state hook basically will store an array with the values which we will select in the checkboxes below, inside the app component.

Image description

This will render the app component like this:
Image description

Realize that in the checkbox input we have a function called "toggleOption"
Image description

This function is responsible to add the item inside our selected state array.

Understanding the function

Let's understand deeper this function...
At the App component in input element of our checkboxes, we are using the function passing the name as parameter

Image description

Let's go to the function
Image description

We are just receiving the previous state of our selected state and assigning the new values, we have also a filter wich remove the items that are equals.

Testing it

To test this i'm using a simple React.useEffect passing our selected state array as dependency.

Image description

Testing it in CodeSandBox

Image description

Checking Example 1

Image description

Checking Example 3
Image description

Unchecking Example 1
Image description

Done!

Feel free to check out this code in CodeSandBox clicking here

Top comments (1)

Collapse
 
gabrieldneto profile image
Gabriel Neto

Nice, this is another way