But, we were kind of stuck there, because our React components were dependent on GraphQL queries. As you can see in our component Pokemon sensors. What should have we done instead? Well, nowadays we tend to create clients who abstract our API works. This gives us more flexibility of how we communicate with the back end. So, for example, for this example, the Pokemon client with the function get Pokemon, and there's my query in it. But, in my component, I can do it the way I want. I could use the use hook to get the information with a suspense. If I want the same functionality as the use query from Apollo, for example, I could use React query from 10 stack, which only handles the management. It's nothing with the API. If I decide that I want to use this API called in a server component, I could simply just call the get Pokemon in the same component, in a React server component. I could also use it in a React native application, because my API is independent from the UI. There are a lot of pieces of code that can be extracted from React components, and this is the first one.
The second one I can give you, this is the last step for today, is the business logic. This logic corresponds to the all the business logic of your product, the kind of logic that you can discuss with a non-programmer. Someone who doesn't know React, well, it's the logic that turns around the business model of your product. For example, let's say you decide to make a shopping website where you have a cart, you can add items to your cart, and you can check out and buy everything. Well, the shopping cart will have logic associated to it. For example, you cannot have minus one item in your cart. That's just not possible. For each item, you can only have a positive quantity. When you open this website, the cart should be initially empty. If the quantity of items changes to zero, I might want to remove the item of the cart. All this logic can be implemented without the UI. This is pure business logic. When the logic could be exactly the same in a single page app, server-side rendering, in an express backend, in a React Native application, then it shouldn't be in a component or a hook. It should be extracted. So, also, by extracting it, you can name all this behavior, and you can even make automated testing easier. What would it look like as code in a component? You could create a simple JavaScript class representing your cart with all these methods that represent how you can manipulate the cart. In this example, you can update the item quantity, you can remove an item, you can count the total amount of items, and we even have a method to create an empty cart. Then, in your component, well, you will have all the UI logic, the state logic of the application.
Comments