You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This improved code centralizes our side effects to an `action` function which takes a `productId` in and passes it to our `reducer` which creates an entirely brand-new cart with this product added to it. This new cart is placed in our `store`, and once that happens all of our components which derive their state from particular pieces of the `store` will be notified by `react-redux` of the new data, and they will update their state and React will intelligently re-render each updated component.
945
+
946
+
This flow makes it possible to be sure that the state of your application can only be updated in one way, and that's through the _action_ -> _reducer_ -> _store_ -> _component_ pipeline. There's no global state to modify, no messages to pass and keep track of, and no uncontrolled side effects that our modules can produce.
947
+
948
+
One caveat to note: now, you might not need Redux in this project's example application, but if we were to expand this code it would become easier to use Redux as the state management solution instead of putting everything in the top-level controller `index.js`. We could have isolated the state of our app there and passed the appropriate data-modifying action functions down through each module. The issue with that is that at scale, we would have a lot of actions to pass down and a lot of data that would live in one massive `index.js` controller. By committing to a proper centralization of state early, we won't need to change much as our application develops.
949
+
950
+
The last thing we need to look at is tests. Tests give us confidence that we can change a module and it will still do what it was intended to do. We will look at the tests for the Cart and Inventory components:
let addToCartBtn =inventoryComponent.find('button').first();
1053
+
addToCartBtn.simulate('click');
1054
+
expect(props.addToCart).toBeCalled();
1055
+
});
1056
+
```
840
1057
1058
+
These tests ensure that the Cart and Inventory components:
1059
+
* Show the data they are supposed to
1060
+
* Maintain a consistent API
1061
+
* Can modify state by calling a given action function
841
1062
842
1063
843
-
You might not need Redux in this specific case, but as we expand this application it will become easier to use Redux as the state management solution instead of linking everything to the parent controller `index.js`
1064
+
## Final Thoughts
1065
+
Software architecture is the stuff that's hard to change, so invest early in a readable, reusable, and refactorable foundation. It will be hard to get there later. By following the 3 Rs, your users will thank you, your developers will thank you, and you will thank yourself.
0 commit comments