To understand it better, let’s say we have an Account list that shows two Account components (Account.cmp). It may look like this:
Visually, the Account list looks like the 1st picture below. But while running, it actually looks something like the 2nd picture:
But, while running, the framework creates an instance of the Controller, an instance of the Renderer for each component but creates only one copy of the Helper and passes the reference of the Helper into every Controller instance and every Renderer instance.
In our example with two Account components, the framework creates one copy of the Helper and passes the reference of this Helper into two controller and to two renderer instances.
- Since Helper is shared across everything, it allows us to share and keep logic across of Controllers and Renderers in one place.
- It also helps us keep logic within Controllers and Renderers lean.
So we should try to delegate business logic to Helpers whenever possible.
Do The Following:
Note: If there are multiple types of components (say, AccountItem.cmp and AccountDetails.cmp), each component type will get a helper of their own.
When To Use Controllers v/s Helpers:
Use Controllers to listen to user events and other events like component, application events. But delegate business logic to helper.
Do similar delegation in all Renderer functions (render, rerender and so on).
Anytime you need to call one controller function from another controller function, move that logic to Helper.
Too many functions in the Helper: If you get into this situation, it’s time to refactor the component itself into smaller sub components.
If you have any further questions, please feel free to add comment below or ping me at: @rajaraodv