Lifting the state up
To implement our Candy Store app, the first thing we must consider is how to access the list of items in the cart. Remember that we can add items to the cart from the products page and manage the cart from the cart page itself. To do this, we need a way to share cart data between these two independent pages.
Although we could technically achieve this using a global or static variable, these approaches are generally considered bad practice in programming for several reasons:
- Global scope: These variables are available from anywhere in your code. As the code base grows, it becomes increasingly harder to track the places where those variables are modified, which can lead to nasty and hard-to-trace bugs.
- Tight coupling: Abstraction and encapsulation are two of the main pillars of object-oriented programming. Following those principles makes the code more maintainable since it’s less coupled, and potential changes can be done in one place instead...