Multiple hooks in Phoenix?

Is it still the case that you can only use one hook per Dom element in liveview? I know you can use one to delegate to others. But it would be way more modular and reusable if you can just have multiple hooks.
Liam :blush:

Only one. You could write a generic one that delegates to others, or, if they are truly independent hooks, wrap your node in a <div> with your second hook.

Thanks for the info. Whatā€™s your take on a generic delegation? Are you thinking, for example, that if there was a need for pointerdown, pointerup, and pointermove listeners, you would have a ā€˜pointerā€™ hook that encompasses them all instead of individual hooks? If thatā€™s the case I would end up with duplicates if I just wanted, say, a pointermove.

Those hooks sound entirely too granular to me. I would think of a hook like a component. The hook should capture all of the behavior of that component that needs to happen at the JS level. A given DOM element simply is only one component, it doesnā€™t make sense to be multiple. Composition would be accomplished by a component that can contain other components.

1 Like

I understand when you say ā€˜think of a hook as a componentā€™. But I canā€™t visualise what you mean by ā€˜contain other componentsā€™. Would you mind showing a super basic example?

I think telling us your use case might be best for guidance.

A hook isnā€™t just ā€œa listener to pointerdown, pointerup, and pointermoveā€, you want to do something with those, right?

Well, Iā€™m trying to think more generally to understand the best approach to using hooks. Iā€™d like to work on JS-heavy features, such as implementing drag-and-drop or drawing with SVGs. However, I want to ensure the code is modular and reusable, similar to how I would structure it with vanilla JavaScript or a framework like Svelte.

For instance, in a drag-and-drop feature, I might have functions that process pointer events, retrieve the client X/Y coordinates, and transform that data into a specific unit. In Svelte, I would make these reusable functions since I might use them frequently across my codebase.

If I combine everything into a single component-style hook, I risk ending up with redundant or repeated code. So Iā€™m looking for general advice on how I can best structure hooks to maintain modularity and reusability while avoiding code repetition

You may be confusing how to structure your JS side code into ā€œlibrariesā€ (functions / classes / etc) and how to structure your hooks. Your hooks are the end-users of your libraries, not your libraries themselves.

Iā€™d recommend to start with actual code and restructure later. You might get lost in remaining very abstract.

Good luck

4 Likes

Thatā€™s actually very helpful. Thank you :blush:

1 Like

A post was split to a new topic: Conditionally loading JS libraries