Frontend AOP — React Hooks vs. Vue Composition API
Hooks are a new addition in React 16.8, I’ve reviewed the essence of that in a previous article
AOP is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns.
React Hooks and Vue 3 Composition API are all about that, lets code and discuss the benefits.
Time to Imagine
Imagine a Large Component (Container / Page) with much logic, it has 3000 lines of code. I know what you’re thinking: “you must have designed it wrong and it could be broken to smaller components”,
I will politely respond that this is not the case as my component deals with the following things:
- Setting User Locale
- Check if the user is still authenticated and redirects them if not
- Track user activity and reacting when the user is inactive for specific period of time
- Listen on an event using EventBus
- Work with a websocket
- Communication with an iframe
- Analytics
- Etc…
Components logic is sometimes split across:
- Props
- Data
- Computed
- Methods
- Watchers
- Lifecycle methods
- Other Components…
We need an effective way to handle those different concerns, we also need a way to group related code together
React Hooks and Vue Composition API are all about that. they help extract the logic and allows putting all related parts together:
In my previous article, I’ve focused on React hooks, so this time let me use some code samples in Vue Composition API that was kind-of inspired by React Hooks:
Here is a simple example of using an EventBus
Here is a more interesting sample:
The composition API helps putting all related parts together
As I see it, in Vue, the hooks approach is meant only for those monster components (I will generally assume, maximum ~20% of the code)
By the other hand, in React the statement is:
We intend for Hooks to cover all existing use cases for classes
Do note that React Hooks (currently?) have some limitations:
- Setup is called repeatedly on each render (produces GC pressure)
- React hooks are sensitive to call order and cannot be conditional
- useCallback is needed in order to prevent inline handlers causing over-re-rendering of child components
- useEffect and useMemo capture stale variables if the user forgets to pass the correct dependency array.
Summary
Both React Hooks and Vue Composition APIs are tools to achieve AOP — Aspect Oriented Programming, which helps building big and none-smelly components and applications, best of luck!