Is your function REALLY a Vue composable?

Sdílet
Vložit
  • čas přidán 27. 07. 2024
  • 💚 Vue's Composition API is amazing and my preferred way to write components nowadays. But often I see that developers don't know when functions are Vue composables, and when they are plain functions. Do you know?
    In this video we will cover exactly this:
    🧠 Explaining what a Vue composable actually is
    ✅ Going through a checklist to figure out if your functions are composables
    🔍 Investigating 4 examples and decide if they are composable or not
    Links:
    🔗 Vue Docs: vuejs.org/guide/reusability/c...
    🔗 Example playground before: play.vuejs.org/#eNqdVc1u2zgQf...
    🔗 Example playground with solutions: play.vuejs.org/#eNqdVVFv2zgM/...
    Don't forget to hit that "Subscribe" button, ring the notification bell and give a thumbs up!
    🌐 Connect further:
    Website: www.lichter.io
    Twitter/X: / thealexlichter
    Twitch: / thealexlichter
    Chapters:
    00:00 Intro
    00:19 Agenda for the video
    00:47 What is a composable?
    02:03 Composable Checklist
    04:06 Determining the Examples
    09:42 Summary
    #Nuxt3 #vuejs #nuxtjs #ssr #serversiderendering #webdevelopment #frontend #frontenddeveloper
  • Věda a technologie

Komentáře • 74

  • @sandros94
    @sandros94 Před 8 měsíci +13

    Damnit, I already see myself next week refactoring a bunch of code...

  • @Lannnister
    @Lannnister Před 8 měsíci +8

    I always wanted to learn the difference between a composasble and just utilitiy functions. Thanks! this was super clear.

    • @TheAlexLichter
      @TheAlexLichter  Před 8 měsíci

      Glad I could help you out on this 🙏🏻🙌🏻

  • @NathanChase
    @NathanChase Před 8 měsíci +5

    If you have composables in your composables directory, where would you put the non-composables? Would you make .ts files that sit right in the same folder with your .vue SFC files, or would you put them in some other "utils" or "helpers" folder?
    I find when I often reach for a composable is when my .vue file's script is getting large and I want to offload some larger functions into separate files, or if I find that there's one or more functions my component is using that I want to reuse for other components.
    I'm also not the biggest fan of having to always prepend "use" - semantically, it often doesn't make any sense to name it "useThing" - so I find myself really not wanting to use that naming convention - even if it has become a common practice.
    I wish there were a lot more videos on conventions for organization of things, because it feels like - even as much as Nuxt does in choosing sensible defaults and conventions - people still find ways of forging their own path for certain things and ways of organizing their repos and code.

    • @TheAlexLichter
      @TheAlexLichter  Před 8 měsíci +3

      Hey Nathan 👋🏻
      I usually put functions that are no composables but should be reused into a `utils` folder indeed - grouping them by "concern".
      For composables, I mainly go for `use` or. `on` which *should* cover most scenarios. If you have some where it feels "unnatural" or "wrong", I'm curious to know more!
      Planning some more code organization video, especially at some point when Multi App Support for nuxt lands 🔥

    • @NathanChase
      @NathanChase Před 8 měsíci +3

      A few more directories I almost always use (that aren’t necessarily standard Nuxt 3) are:
      /types
      (for all your .d.ts declared type interfaces)
      /packages
      (If your repo is a monorepo, shared package.json devDeps go in here)
      /config
      (I like to pull out any huge chunks of nuxt.config and put them in individual config .ts files here)

    • @Shulkerkiste
      @Shulkerkiste Před 8 měsíci +1

      I always outsource *everything* which doesn't interact with Vue into a script file. Therefore, the Vue files are much shorter and easy to read.
      My folder structure could look like this:
      scripts folder:
      users.js
      authentication.js
      dashboard.js
      todos.js
      helpers.js
      composables folder:
      users.js
      event-listeners.js
      ...

  • @marcin_nieznaj
    @marcin_nieznaj Před 8 měsíci +6

    Great job, please make these more insightful Nuxt videos

    • @TheAlexLichter
      @TheAlexLichter  Před 8 měsíci

      Thank you Marcin 🙏🏻 I'll keep them coming! Is there anything specific you'd like to know more about in the Vue and Nuxt world?

    • @marcin_nieznaj
      @marcin_nieznaj Před 8 měsíci +1

      @@TheAlexLichter I deal with very project specific issues on daily basis so nothing in particular interests me at the moment. But seeing you go deeper into various Nuxt details by itself would be great

    • @TheAlexLichter
      @TheAlexLichter  Před 8 měsíci +1

      @marcinnieznaj5666 will put more “nuxt in-depth” content on the list 👍🏻

    • @Microphunktv-jb3kj
      @Microphunktv-jb3kj Před 8 měsíci +1

      6:45 , i guess thats why nuxt framework has 2 folders... one for composables.. and other utils for just helper/utility functions... :D

    • @TheAlexLichter
      @TheAlexLichter  Před 8 měsíci

      Exactly 👌🏻

  • @olatunjiolakunle6908
    @olatunjiolakunle6908 Před 8 měsíci +1

    This video answer the question I ask the other day on one of your videos, Thanks Alexander

  • @rahman9418
    @rahman9418 Před 8 měsíci +1

    Waiting for the next video, I will always look forward to it, Thank you very much Alexander

    • @TheAlexLichter
      @TheAlexLichter  Před 8 měsíci

      Delighted to hear that 🙏🏻 any favorite video so far? ☺️

    • @rahman9418
      @rahman9418 Před 8 měsíci

      @@TheAlexLichter everything

  • @chstappert
    @chstappert Před 8 měsíci +1

    You have a hand in the topics which matter the most.

    • @TheAlexLichter
      @TheAlexLichter  Před 8 měsíci

      I'm very happy that you think so! 🙏🏻Hope the examples helped understanding when a Vue composable is a composable 😋

  • @виртуоз_ру
    @виртуоз_ру Před 8 měsíci +3

    Вопросов нет. Всё ясно и понятно. Благодарю 👍

    • @TheAlexLichter
      @TheAlexLichter  Před 8 měsíci +2

      Рад это слышать, приятель 👏🏻

  • @brahim_boussadjra
    @brahim_boussadjra Před 8 měsíci +2

    Thank you for this informative video. I think the best name of composables that hold only lifecycle hooks is onX instead of useX, also you forget to add dependency injection in the checklist

    • @TheAlexLichter
      @TheAlexLichter  Před 8 měsíci +1

      Hey Brahim! Good points. I would use the `on` prefix for "reactions", e.g. onKeyPressed or onResumePage, which are not necessarily tied to lifecycle hooks but more as "reaction to changes/state". ☺️
      DI is a good point indeed - though that also means dealing with state in a way so I might get away with categorizing it into the "stateful" rule here 😇

    • @brahim_boussadjra
      @brahim_boussadjra Před 8 měsíci +1

      ​@@TheAlexLichter thank you for reply

  • @Ayvengo21
    @Ayvengo21 Před měsícem +1

    That would be more usefully to get some examples of common problems solved by composable. Like for example should i made some of those as a wrapper or maybe a plugin would be better let say for a case when i have to check for 401 every time. Where else composable could make my life easier and just not over complicate an app for no good reason.

  • @OttoPaulsen
    @OttoPaulsen Před 8 měsíci +2

    Thank you for a clear and good explanation. I was wondering about that user function that you determined was a composable, and renamed to useUser. That user ref in there, should not that normally be defined outside the function? At least if you want all the users of that composable to share it?

    • @TheAlexLichter
      @TheAlexLichter  Před 8 měsíci +1

      Hey Otto! Thank you for the kind words 🙏🏻
      It depends a bit what it is used for, but yes, putting the ref outside would create global state, which can be desired in this case! When using Nuxt though, I'd rather go with useState + keep it inside because that way I create global state without "leaving the Vue context" 😋

  • @irinakats8008
    @irinakats8008 Před 3 měsíci

    Thanks, after reading the docs I couldn't see the difference, now I do

  • @matanon8454
    @matanon8454 Před 8 měsíci +1

    This helped me so much thanks 🙏

  • @Tarabass
    @Tarabass Před 8 měsíci +1

    One of the rules I miss is re-usability. I see composables like some kind of mixins and composables should only be created when the functionality is re-used, like so for mixins. So I would like to add a rule:
    Is the function used in multiple places?
    Correct me if I'm wrong :)

    • @TheAlexLichter
      @TheAlexLichter  Před 8 měsíci +1

      Hey! Yes and no. You can also have composables that are extracted but live in the components (or an extra file) and are not reused, purely for grouping ☺️

  • @jesusguerrero9515
    @jesusguerrero9515 Před 8 měsíci

    Thanks for the info. Very clear.

  • @moe8055
    @moe8055 Před 8 měsíci +1

    Thanks alot Alex! Greets from Düsseldorf

    • @TheAlexLichter
      @TheAlexLichter  Před 8 měsíci

      My pleasure! Greetings back from AMS 🙌🏻

  • @bernattousfiga
    @bernattousfiga Před 5 měsíci +1

    Great explanation and tips Alexander!
    I'm doing a bit of refactoring now 😅
    What about the classes? Should I check the checklist for all methods of the class and, if at least one method acomplish one of the conditions, it means the class is a composable? How would you approach it?
    Thanks in advance!

    • @TheAlexLichter
      @TheAlexLichter  Před 5 měsíci

      To be fair, I almost never use classes as abstraction in the frontend. I'd suggest to make them as "composable-free" as possible and use actual composables to work with classes, e.g. as I've shown with the repository pattern czcams.com/video/jXH8Tr-exhI/video.html

    • @bernattousfiga
      @bernattousfiga Před 5 měsíci

      @@TheAlexLichter Thanks for the answer! I'll try to follow these suggestion 😊

  • @chiebidoluchinaemerem5860
    @chiebidoluchinaemerem5860 Před 8 měsíci +1

    "The mouse on the page" got me real good 🐁

  • @MissedWarrior
    @MissedWarrior Před 8 měsíci +1

    Hey! Great video, thanks for it. What do you think about inject? Will it turn function to composable? I think yes because it requires vue injection context

    • @TheAlexLichter
      @TheAlexLichter  Před 8 měsíci

      Yes! Definitely also a composable - provide/inject is another way for handling state so that counts too 👌🏻

  • @MuhammadKhizar7
    @MuhammadKhizar7 Před 8 měsíci +2

    Thanks for the video. what about using composables as service layer (fetching data) and then using it in setup? Will it breach convention?

    • @TheAlexLichter
      @TheAlexLichter  Před 8 měsíci +1

      If you handle the state (think of sth like useFetch) it is fine
      If it is just a fetch function (like the Fetch API or $fetch), it would be a utility!

  • @m0ksem
    @m0ksem Před 8 měsíci +1

    Hi. You said composables can be used in lifecycle hooks. Do you have a good example of this scenario? I feel like composables should compose component only in setup fn or other composables.

    • @TheAlexLichter
      @TheAlexLichter  Před 8 měsíci

      I wouldn’t advise it but the *can* in some scenarios (according to the docs) I think I never used it but possibly when working with SSR and depending on window or document - but there are IMO nicer workarounds there

  • @andogrando487
    @andogrando487 Před 4 měsíci

    I've always struggled with deciding when something is a composable and when I should be using pinia or something to manage... maybe there is no case for pinia anymore since you technically could do almost all of it with a composable....

    • @TheAlexLichter
      @TheAlexLichter  Před 4 měsíci

      Pinia is eventually also a "very refined composable" :D
      And it still can be valuable, depending on what kind of app you build and what needs you have. Especially plugins, devtools integration, a clear data flow etc. etc. can be pretty helpful for the DX.

  • @markcasiano6501
    @markcasiano6501 Před měsícem +1

    Hello, I am coming from your video "You are using useFetch WRONG!", and this is my scenario. I wrote a couple of composables that uses useFetch, which is a real composable(as per this video). Now, some of these composables uses that composable(nested). But I am going back to the problem "Component is already mounted, please use $fetch instead." which will be fixed if I use $fetch. My question is, if I change useFetch to $fetch, does that mean it is not composables anymore? Thanks.

    • @TheAlexLichter
      @TheAlexLichter  Před měsícem

      Using a nested composable seems fine. The question is where the top-Level composable itself is called 👀

    • @markcasiano6501
      @markcasiano6501 Před měsícem

      @@TheAlexLichter I get it, I found out that the warning was caused by watchEffect(), because it is executed twice on a direct page load.

  • @The4tticuz
    @The4tticuz Před 6 měsíci

    Thanks for that great video which makes it really clear.
    But I guess there is another question: is your composable a composable or a plugin?
    Can you help me with this or is it planned for another video?
    Thanks alot

    • @TheAlexLichter
      @TheAlexLichter  Před 6 měsíci

      Hey! Interesting - Do you have an example where it is rather unclear?

    • @The4tticuz
      @The4tticuz Před 6 měsíci

      @@TheAlexLichter it's more a general question referring to your question (util function vs composable). I find myself some time getting stuck in trying to answer to myself is this particular function might be set up as a plugin or a composable. And I think it's not that easy... or Im just overthinking those concepts.
      A simple example could be: fetching data like products, which are only needed on that particular page, not stored and/or used in other components

    • @TheAlexLichter
      @TheAlexLichter  Před 6 měsíci

      @The4tticuz I’d mostly go for a composable in this case. A plugin is useful if you need to provide a „global helper“, eg a custom $fetch instance 👍🏻

  • @syahminawi4733
    @syahminawi4733 Před 10 dny

    Question! if 2 component calling the same composable, did it create different instance of that composable or they are sharing the stateful value?

    • @TheAlexLichter
      @TheAlexLichter  Před 10 dny

      Same as with JavaScript functions -> a different instance.
      If you use a ref *outside* of a composable though, it acts as global state. This shouldn't be done when using SSR though (for that you use useState).

  • @anthonynicholls7
    @anthonynicholls7 Před 5 měsíci

    If my composable has global state in Nuxt 3 or uses say a pinia store would that make it a composable?

  • @nishantrai982
    @nishantrai982 Před měsícem

    why am I able to use the useFetch composable inside a util function in /utils directory?

    • @TheAlexLichter
      @TheAlexLichter  Před měsícem

      Nobody "formally" restricts you to use it in `utils` *but* your "util" is then a composable. So it is not correct 😋

  • @EvestDev
    @EvestDev Před 2 měsíci

    Hi Alex, i have a question. I think i use composables a bit wrong. I use them just for the autoimport sake. For example i have one super simple one that just resolves a promise after a given number of miliseconds. I used them like some helper functions. But the question is, where should i put those files in my nuxt project if not in the composables directory?

    • @TheAlexLichter
      @TheAlexLichter  Před 2 měsíci +1

      Hey Evest 👋🏻
      Yes, that's not entirely as intended. You have "utility functions" there which I'd put in the utils folder. These shouldn't have a "use" prefix but are also auto imported! 😋

  • @joshdeltener2012
    @joshdeltener2012 Před 8 měsíci +1

    // is this a composable? Even though it's a bit silly, I say yes! Technically it has state.
    const keys: Record = {}
    export default function (key: string, callback: Function) {
    if (keys[key] === true) return
    keys[key] = true
    callback()
    }

    • @TheAlexLichter
      @TheAlexLichter  Před 8 měsíci +1

      I'd say it is no composable as managing the state happens through exposing global state and not through reactive references 😋
      You can easily run it outside of the Vue context in any browser or Node enviroment 👍🏻

  • @Microphunktv-jb3kj
    @Microphunktv-jb3kj Před 8 měsíci

    8:10 , if u didnt know computed is also ref , u only mention user as stateful logic... eventho computed is not ment to be mutated/create side-effects

    • @TheAlexLichter
      @TheAlexLichter  Před 8 měsíci

      If you have a computed in a composable, then somewhere in there should also be a ref 👀
      Can be as input or as initialized variable ☺️

  • @youhan96
    @youhan96 Před 6 měsíci +1

    Clear as mud sir! Just kidding

    • @TheAlexLichter
      @TheAlexLichter  Před 6 měsíci +1

      😜
      Hope it helped ☺️

    • @youhan96
      @youhan96 Před 6 měsíci

      @@TheAlexLichter I kind of khew them but how you put that into 3 simple rules was super clear.