Day 14 of 100days of code

Hello and welcome to Day 14 of my challenge! πŸ˜€πŸ’ͺ

Derived state in practice:

So I'm going to start by adding some JSX to the Stats component.

The footerπŸ‘‡πŸ‘‡.

Now, some JSX πŸ‘‡πŸ‘‡πŸ‘‡

Looks like this nowπŸ‘‡πŸ‘‡

Now, we need to find a way to figure out the number of items on our list and how many we have already packed, and display it in the Stats component.

Wrong way:❌❌

The incorrect approach is to use state directly. You might consider creating a state variable, perhaps called 'nums,' in the Stats component to represent the number (X) for the items in our list. For example, you could go to the App component, create a state, and use the setNums function to update it when an item is added to the list. This involves placing the updater function inside the function that adds an item to the list (handleAddItem), like soπŸ‘‡πŸ‘‡

So, the setNums function increments the current value nums by 1 every time we add an itemπŸ‘†

Next, we have to pass the 'nums' as props to the Stats componentπŸ‘‡πŸ‘‡

Next, we destructure the props in the Stats component and use it in the JSX like soπŸ‘‡πŸ‘‡

So now, when we add an item to the list, the value of 'nums' will be increased by 1.πŸ‘‡

However, having multiple independent state variables may lead to unnecessary re-renders of the component. I also realized that deleting the item added to the list does not change the 'nums' value from 1 back to 0.πŸ‘†πŸ‘†.

Correct way:βœ”βœ”

The best way to do this is to use the derived state approach. This involves deriving 'nums' from the 'item' state variable instead of creating a separate state for it, like so at line 11πŸ‘‡. Remember to undo the previous codes

"Deleting an item from the list updates the 'nums' displayed on the footer in this case.

Now, instead of passing in 'nums' as props to the Stats component as in the image above, let's pass in the 'items' array instead and derive the value of 'nums' in the Stats component where we use it. Line 24πŸ‘‡πŸ‘‡

Now, in the Stats componentπŸ‘‡

Now, let's add the other value for our packed items in the Stats component. In the Stats component, I'm going to derive the number of packed items from the 'items' array like so πŸ‘‡πŸ‘‡. Line 4

Next, we calculate the percentage like so .πŸ‘‡ Line 5

See resultπŸ‘‡

Now, let's display a different text when it is packed to 100%.πŸ‘‡.

If there are no items in the list yet, it is unnecessary to return either of the texts. Now, we are going to demonstrate a good use case for early return πŸ‘‡ Line 3.

Now, when no item has been added, it will display like thisπŸ‘‡πŸ‘‡

Thank you for readingπŸ’ͺπŸ’ͺ

Β