Design patterns are established solutions for common software architecture problems. As a JavaScript developer, I encounter a lot of problems, and design patterns are there to solve a lot of them. Some of the very popular libraries are also utilizing these design patterns. Here I listed a couple of design patterns I am using with different JavaScript libraries.
Observer Design Pattern
- MobX
We do use observer design patterns in the MobX store management library. With MobX, we consider a subject that will change over time. There is a couple of subscribers method, that will run on the change of the subject.
Command Design Pattern
- DB Transactions
The command design pattern provides undo operation. It is applicable when we need to undo some operation after executing the operation. We use this design pattern in database transactions. In the database transactions, if there is any failure in any of the operations, we undo each of the previous operations.
Proxy Design Pattern
- Caching in route and DB
In a traditional caching mechanism, we first check if the data is already there or not. If data already exists in the cache, we return the data from the cache and do not perform operations. Otherwise, fetch/gather the data, update the cache with the data, and then return the data. This architecture represents the proxy design pattern.
Facade Design Pattern
- Wrapper for API call (Axios/fetch)
For data fetching operations, from UI to API, we can use any popular library like axios or fetch. Now, to make the Axios or fetch library abstract, we used a wrapper module. This wrapper hides the functionalities of the library. It is helpful if future, we do want to change the library and we do not want to change the high-level codes.
- Payment Module (Stripe/Paypal)
Another example can be payment modules, a wrapper can be helpful if there is a chance to change the module. For example, right now we are using Stripe but maybe in the future we will use Paypal instead.
Singleton Design Pattern
- React hook forms
React hook forms have a feature called watch
where we can observe the changes in a particular field of the form. Our requirements were to observe the changes outside of the form. In this case, we needed the watcher to be extracted from the form. But getting the watcher from the hook-from makes the form initiate each time.
So in this case, we use the singleton pattern in the hook form, so it will not initiate more than once and provide the watcher from the first-time initiated object.
Null Object Pattern
- Redux Toolkit Initial State
In the redux toolkit, when we need data to be fetched from the API, we declare an initial state. This initial state is a fallback of actual data. It provides the application not to break down or crash until the actual data is being fetched and the state is being updated.