Day 14 of 100days of code
Hello and welcome to Day 14 of my challenge! ππͺ
Table of contents
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πͺπͺ