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
After this we have our App component which have a simple useState hook initializing with an empty array
This state hook basically will store an array with the values which we will select in the checkboxes below, inside the app component.
This will render the app component like this:
Realize that in the checkbox input we have a function called "toggleOption"
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
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.
Testing it in CodeSandBox
Checking Example 1
Done!
Feel free to check out this code in CodeSandBox clicking here
Top comments (1)
Nice, this is another way