Always Use a Custom Hook for Context API, Not useContext (React Context API, TypeScript)

Поделиться
HTML-код
  • Опубликовано: 14 май 2024
  • Hi, I'm Wesley. I'm a brand ambassador for Kinde.
    👉 NEW React & Next.js Course: bytegrad.com/courses/professi...
    👉 Professional JavaScript Course: bytegrad.com/courses/professi...
    👉 Professional CSS Course: bytegrad.com/courses/professi...
    👉 Discord: all my courses have a private Discord where I actively participate
    🔔 Email newsletter (BIG update soon): email.bytegrad.com
    ⏱️ Timestamps:
    0:00 Intro
    0:07 Context example
    1:04 Wrap app with context
    1:42 Client component
    2:13 Consuming context (useContext)
    3:09 First problem
    3:20 Second problem
    4:18 Check for null
    4:47 Custom hook
    5:45 Consume context
    6:18 Context API TypeScript typing
    6:27 Component props type
    6:37 Context type
    7:51 'Light' | 'Dark' type
    8:34 Theme type
    8:48 Type alias vs Interface
    9:03 setTheme type
    #webdevelopment #programming #coding

Комментарии • 192

  • @ByteGrad
    @ByteGrad  2 месяца назад +2

    My Professional React & Next.js course is OUT NOW now! Find it here: bytegrad.com/courses/professional-react-nextjs -- this is the #1 resource to master the latest React & Next.js, my absolute best work.

  • @revillsimon
    @revillsimon 9 месяцев назад +95

    What I like about your videos is how you cover a lot of up-to-date info and techniques very quickly, thoroughly, and it is very concise and to-the-point. Thank you 🙏

    • @ByteGrad
      @ByteGrad  9 месяцев назад +4

      I appreciate that!

    • @noobgam6331
      @noobgam6331 8 месяцев назад

      Funny how people praise the default non-language specific convensions (DRY in case of this video)
      Just goes to show how low the bar for becoming an SDE is nowadays

    • @UsernameUsername0000
      @UsernameUsername0000 7 месяцев назад +5

      ⁠@@noobgam6331 Was this comment necessary? Lol. I don’t see your point. This is a genuinely useful refactor that not everyone might’ve considered, and it’s presented concisely with TypeScript and the latest version of Next 13. Don’t see how the ‘bar is low’ when this covers the ‘how’ of DRY instead of just the ‘what.’

    • @VincentJenks
      @VincentJenks 7 месяцев назад +1

      Agree. So well done. No fluff, no 5 minutes of chatter, self-aggrandizing, blah…just right to the point. I’m looking forward to your React course even though I’m very experienced, because I know I’m going to learn some new things and not waste any of my time. Most teachers and dev content creators could learn from this guy!

  • @youneshenni5417
    @youneshenni5417 9 месяцев назад +16

    This is the first time I see the logic to make sense of this pattern. Well done.

  • @krsnamara
    @krsnamara 3 месяца назад +1

    Really really great video here. I am learning typescript, useContext and next.js right now. Spent the past few days trying to sift through the different resources. This video here really dug into the details of some of the issues I was running into. Thank you much for taking the time and sharing the knowledge with clarity.

  • @n8guy
    @n8guy 2 месяца назад +1

    EXCELLENT step-by-step teaching! Really well done.

  • @rayaqin
    @rayaqin 5 месяцев назад +1

    the thought process and the flow of work is very clear and that makes these videos super satisfying to watch, thanks : )

  • @laputafelix
    @laputafelix 8 месяцев назад +3

    omg, those step-step-step typescript trouble shooting DOES help me getting out of the type-hell I’ve been to recently.
    So far the best tutor in the context of typescript/nextjs combined.

  • @shreyasvaidya9552
    @shreyasvaidya9552 9 месяцев назад +2

    I work with Context a lot and learnt something new and its very useful. I will be using it a lot. Thank you sir. Keep up the great work.

  • @maykefernandesdossantos7374
    @maykefernandesdossantos7374 8 месяцев назад +2

    Great intro to good practices using context and custom hooks!
    Nice that you focused on Typescript cleanup as well!

  • @martapfahl940
    @martapfahl940 9 месяцев назад +3

    I love that nowadays every Tutorial is in Typescript =) Thanks!

  • @JoeyMa
    @JoeyMa 8 месяцев назад +6

    I love this! It sounds like you would be the type of person who would take the time to understand something fully (or decently well), and it shows from the way you explain your thoughts! If I may, I would also love to hear your take on named imports over ‘import React from “react”’. Based on my previous research the production code should properly tree-shake the unnecessary code to reduce bundle size, (when you’ve properly configured your webpack or if you’re using some framework like Next.js); however, having generous imports eventually slows the dev experience such as during ‘npm run dev‘ or ‘npm run build’. Or even a video or references on this would be cool!

  • @LeonardoJaquesDev
    @LeonardoJaquesDev 6 месяцев назад +1

    This content helped me a lot. The code just got cleaner and smarter. I will follow you for more precious infamations like this. Thank you, keep up the good work

  • @lillenk125
    @lillenk125 8 месяцев назад +1

    Holy S**T I'm happy I found you. So educational. After watching so many other videos were people explain things I just find myself still not really getting it. But this made me get it. This is gold!

  • @ekanemeno4565
    @ekanemeno4565 7 месяцев назад +1

    Thanks a lot for this. You have re-ignited my love for React

  • @bdeink
    @bdeink Месяц назад +1

    I don't normally comment on videos, but this really helped me out. Great work, and thanks!

  • @flameofheartsflameofhearts3955
    @flameofheartsflameofhearts3955 5 месяцев назад +1

    Thank you man, I was having some problems while making a darkmode in react, cuz I am kinda new to all these context and custom hooks, but after watching ur video I got it all done fast 🙏

  • @Xe054
    @Xe054 8 месяцев назад +3

    I really enjoyed this video! Even the scary Typescript part was easy to understand. The only feedback I'd like to share is that the steps in working with React Context could have been emphasized more (it's so easy to miss if you don't pay close attention). Since Context is hard for beginners to grasp, perhaps talking about the 3 step process of Create, Provide, and Consume (CPC) before diving into the code would have helped. Also, showing the 3 steps as a text overlay in your video would've been a nice bonus! You did a great job of describing why you would even need context (for theming) and I also learned some new things today. Thank you!

  • @njahncke
    @njahncke 8 месяцев назад +1

    Excellent video. I truly appreciate the additional ts debugging info you provided! Very valuable.

  • @UmeshKumar-mt2dp
    @UmeshKumar-mt2dp 3 месяца назад +1

    You're doing an awesome job, byte !! Lots of love !!💗❤❤

  • @VLADICA94KG
    @VLADICA94KG 9 месяцев назад +7

    Thanks for the great, concise, and useful content! Keep up with the great work!

    • @ByteGrad
      @ByteGrad  9 месяцев назад +1

      Thanks, will do!

  • @nicolascuor2378
    @nicolascuor2378 6 месяцев назад +1

    Informative and concise, very good. Many thanks from Italy.

  • @thompsaa
    @thompsaa 6 месяцев назад +1

    Thank you! This was incredibly helpful and explained very well. :)

  • @victorduarte4059
    @victorduarte4059 7 месяцев назад +1

    Thank you for the lesson I will be using this on my personal project.
    Had a question out of scope, what options do we have if we wanted to toggle theme on the tag which is outside the provider?
    I assume the options are to rely on JS or move the provider higher in the DOM wrapping the tag but the later would require making the layout a client component...

  • @abbaskareem5281
    @abbaskareem5281 8 месяцев назад +1

    I consider this video as a source of truth for using best practice on implement context api . Thank you very much sir ❤

  • @datasagedev
    @datasagedev 5 месяцев назад +1

    Thank you, very well explained and easy to grasp.

  • @chrisauret3785
    @chrisauret3785 8 месяцев назад +2

    +10 for showing how to implement the typescript version thoroughly

  • @nicolamigone8849
    @nicolamigone8849 8 месяцев назад +1

    Your voice is so calming! And the content is amazing. Subscribed

  • @acloudonthebluestsky9687
    @acloudonthebluestsky9687 6 месяцев назад +1

    i just learnt this from old project, really great way to use

  • @apuravela
    @apuravela 4 месяца назад +1

    Thanks! Really clear explanation! Congratulations on such a good video

  • @Clem.E
    @Clem.E 8 месяцев назад +1

    Incredibly clear video. Thank you very much.

  • @zackarybrumfield2
    @zackarybrumfield2 6 месяцев назад +2

    This is the first video I've watched that focused on error handling as in depth as you have. I've watched several useContext videos over the years and I can't really recall someone who focused on the the idea that your context will be null. Or maybe I just haven't searched hard enough lol. This gave me a better idea on how to handle context errors in my app.

    • @iamsarb_0017
      @iamsarb_0017 6 месяцев назад

      yup very Few Videos are there related to Context in null

  • @SohibjonAbdialimov
    @SohibjonAbdialimov 5 месяцев назад +2

    This lesson is very understandable and fun. Good Luck Teacher. Thank you✔✔

  • @throwaway-lo4zw
    @throwaway-lo4zw 3 месяца назад +1

    Loved seeing how u debug typescript errors, learned a lot from that

  • @ivandamyanov
    @ivandamyanov 9 месяцев назад +3

    Thank you for the great video, a lot of small things to help me up my rank from beginner to experienced beginner ^^ Was good to understand also the typescript union when used with useState!

  • @faroukdourmane7632
    @faroukdourmane7632 8 месяцев назад +1

    Perfect explanation, Thanks !

  • @6th.player
    @6th.player 7 месяцев назад +1

    I got hooked! thanks man!

  • @scherschak
    @scherschak 3 месяца назад +1

    Thanks a lot! Super easy to understand

  • @jhonnynasc
    @jhonnynasc 6 месяцев назад +1

    Thank you, your videos are very informative and easy to understand, even for a non native or proficient english speaker like me

  • @Alessandro-nq3tm
    @Alessandro-nq3tm 8 месяцев назад +2

    As a web dev, great content! Subscribed!

  • @franklinantony
    @franklinantony 9 месяцев назад +3

    Damn you are really good at explaining everything. Hope I get someone like you as my senior.

  • @mikro_rimoslav
    @mikro_rimoslav 2 месяца назад

    I really like your videos, you keep them short, on point and informative about pretty up-to-date technologies.
    What I'd like to add to this video is that many times you only need a hook without a context.
    And in other places you need that same hook but with a context provider.
    That issue is solvable by putting [theme, setTheme] logic into a custom hook, and by calling it inside ThemeContextProvider.
    But even more frequently, you may need to call a hook, do something with its values, maybe pass them to another hook and then return context provider for the components down tree.
    And on a different place in your project you need to call that same hook, and just return context provider, like in your example.
    This logic binds hook and context together without flexibility, which is not ideal for complex projects.
    It's much better practice to abstract away provider factory separately from hooks.

  • @Miguel-em2yj
    @Miguel-em2yj 9 месяцев назад +2

    I mean, wow! I just found your channel and i already love it, thank you for sharing your knowledge, keep making videos like this please!

    • @ByteGrad
      @ByteGrad  9 месяцев назад +1

      Thank you! Will do!

  • @meka4996
    @meka4996 7 месяцев назад +1

    You are the TypeScript man! Thanks

  • @victorumeh3768
    @victorumeh3768 9 месяцев назад

    Lucky to bump into this, had something similar I've been trying to fix, bless you❤️

  • @lemondigitaldesign
    @lemondigitaldesign 5 месяцев назад +1

    Thank you! Now I know why! I have been doing it this way, simply for convenience but was wondering whether this was actually the right way. Lucky punch I guess :P
    I was actually googling to find the "official" way of doing it, just to make sure I wasn't doing anything stupid that could bite me later down the line.
    Now I know what I had is indeed correct and why, and I understand the underlying logic. Plus I learnt a couple of handy tips along the way!
    Awesome! Keep up the great work, I always enjoy following you through your insightful content!

  • @odanabunaga2505
    @odanabunaga2505 8 месяцев назад +1

    superuseful, thanks!

  • @austincodes
    @austincodes 9 месяцев назад +1

    Great video. If you’re using next I highly recommend looking into the next-themes package if you want to make it stupid simple

  • @zivtamary
    @zivtamary 9 месяцев назад +1

    thanks :) made my contexts a lot cleaner

  • @MrZiyak99
    @MrZiyak99 9 месяцев назад +1

    great vid I had a question. if we wrap a server component inside a client component will the server component wait for the client that it's a child of to be hydrated before it loads?

  • @cosmo-rodrigues
    @cosmo-rodrigues 4 месяца назад +1

    What a class, man. What a class!

  • @musiuralamopu9589
    @musiuralamopu9589 4 месяца назад +1

    Very useful and easy to catch the concept

  • @zhenglaowang8489
    @zhenglaowang8489 8 месяцев назад +2

    In TypeScript you can also wrap your interface/type within `PropsWithChildren` instead of manually specifying it in your type.

  • @7doors847
    @7doors847 8 месяцев назад +1

    A great late discovery (for me).
    Impressive channel and content.
    Subbed!

  • @builtdifferent3350
    @builtdifferent3350 8 месяцев назад +1

    Glad I found your channel

  • @UwU-dx5hu
    @UwU-dx5hu 3 месяца назад +1

    Thank you so much❤

  • @abdelfadeel0
    @abdelfadeel0 4 месяца назад +1

    great explanation ❤

  • @MuhammadHaseebAhmed
    @MuhammadHaseebAhmed 9 месяцев назад +1

    Great !! btw brother wich extension is you are using for code suggestion.

  • @snivels
    @snivels 9 месяцев назад +14

    Excellent video, as always. The concise way you explain things, as well as the extra information and "gotchas" you always provide as you explain are top class.

    • @ByteGrad
      @ByteGrad  9 месяцев назад

      Thanks a lot, appreciate it

  • @riteshkc814
    @riteshkc814 4 месяца назад +1

    I think this year i'll get promoted from junior to mid, thanks to you.

  • @yashdubeyofficial
    @yashdubeyofficial 8 месяцев назад +1

    at last someone is going deep into react and the TS solution part is OG

  • @SSango-hk9sm
    @SSango-hk9sm 7 месяцев назад +1

    duuuuude!!!!!you got my sub!

  • @nilkanthpatadiya9524
    @nilkanthpatadiya9524 8 месяцев назад

    Was trying to solve null error while destrucuring react context , very useful video ❤

  • @fabianpetersen2452
    @fabianpetersen2452 4 месяца назад +2

    Nicely done, im learning typescript and get confused a lot with the types 😅. I've been using the useContext hook a lot in previous projects without typescript, changing to types and setting this up was no fun while learning. This is the best tutorial I could find on this topic explaining exactly how i would set it up minus types. I just wish to know how do you use a global context file to manage all your state using types, that could be messy in one file?

  • @Yobo77
    @Yobo77 9 месяцев назад

    Great explanation! Nice job! 🙂

    • @ByteGrad
      @ByteGrad  9 месяцев назад

      Thank you! 😃

  • @salvadorbalas5234
    @salvadorbalas5234 8 месяцев назад +1

    Amazing job! every interesting approach. Can you make more videos about fixing typescript issues like you did after 6:18 they are very awesome and I like the tips u're giving like the hover over setTheme for example! thank you!

  • @hbela1000
    @hbela1000 4 месяца назад +1

    crystal clear.

  • @alejandroyanes391
    @alejandroyanes391 8 месяцев назад +1

    amazing !

  • @andrewraj3846
    @andrewraj3846 9 месяцев назад +18

    Nice and very informative. Can you speak louder

    • @ByteGrad
      @ByteGrad  9 месяцев назад +3

      Thanks, will do

  • @ThanHtutZaw3
    @ThanHtutZaw3 8 месяцев назад

    when using multiple value from context and de structure in component , some values are need to destructure without actual needs. So I have to add types theme?:string in context types . How can I fix that ?

  • @balduin_b4334
    @balduin_b4334 9 месяцев назад +1

    great video!

  • @victorsaisse1340
    @victorsaisse1340 9 месяцев назад +2

    that was an awesome explanation

  • @erce_
    @erce_ 8 месяцев назад +1

    Good stuff, thanks

  • @yusufkaymaz647
    @yusufkaymaz647 7 месяцев назад +1

    great video thank you :)

  • @hugopinho9534
    @hugopinho9534 6 месяцев назад +1

    Amazing!!

  • @Ali-ei3mg
    @Ali-ei3mg 9 месяцев назад +1

    Thanks I learn a alot from this video

  • @Mitsunee_
    @Mitsunee_ 8 месяцев назад +1

    Good video, thanks for the clarification about client components that accept children. I was unsure if this works similarly to Astro, which appears to be the case and is the best case scenario.
    Small suggestion for the types: React already has a React.WithChildren type which would be good enough here, no need for a type alias. This type is also generic so you can wrap it around any object type like React.WithChildren. I don't see this type used often as most of the time you're representing an HTML tag with ComponentProps instead, which already includes the children prop. ReactNode should only be used like this when a child element is absolutely required.

  • @Fanaro
    @Fanaro 8 месяцев назад +1

    Looking forward to your React course!

    • @ByteGrad
      @ByteGrad  8 месяцев назад

      It's very close. Make sure you're subscribed to the email newsletter :)

  • @Its-InderjeetSinghGill
    @Its-InderjeetSinghGill 3 месяца назад

    A small tip there you could also extract the theme union type like this: ThemeContext[“theme”] instead of creating it separately but nothing wrong with your implementation but just a small trick I wanted to share hope that helps.

  • @nogafouz2174
    @nogafouz2174 7 месяцев назад +1

    good video thanks

  • @thaigia6759
    @thaigia6759 3 месяца назад +1

    Thank you for your video, verry helpful but I have a question:
    I got an issue with your code, if the type of context is ThemeContext or null then if we have a line of code like below:
    const {theme}= useThemeContext() it will have error that the value return can be null so that can not get theme value from that, and I dont want that. Can I just set the type of context is just ThemeContext and dont have null, then we need to set default value for this type, is this ok?

  • @haniseanda
    @haniseanda 9 месяцев назад

    Just Learned typescript and type checking on a 9min video❤‍🔥💯

  • @gabrielokundaye1502
    @gabrielokundaye1502 9 месяцев назад +1

    Great!

  • @user-iu9ej9gr8l
    @user-iu9ej9gr8l 4 месяца назад

    Hi! Is there a possibility to use custom hook to get context in server components?

  • @prakharagarwal5929
    @prakharagarwal5929 3 месяца назад +1

    Great info. Which theme are you using in vscode?

  • @pagarevijayy
    @pagarevijayy 2 месяца назад +1

    👍 wonderful video

  • @vanijatkosolomichev9452
    @vanijatkosolomichev9452 3 месяца назад +1

    Smart... 👌

  • @thaifred
    @thaifred 6 месяцев назад +1

    Is the reason to set the initial value to null so you can check if its being used outside the provider? Or why not define it as an object?

  • @darkwoodmovies
    @darkwoodmovies 8 месяцев назад +1

    If you type and set up `ThemeContext` correctly, then `const { theme } = useContext(ThemeContext);` is all you need and it won't have any issues out of the box. Just do something like `const ThemeContext = createContext({ theme: DEFAULT_THEME, setTheme: () => throw Error('Not implemented'); })` and then no more null values or type problems

  • @tahamanna3600
    @tahamanna3600 3 месяца назад +1

    great video

  • @luar4165
    @luar4165 8 месяцев назад

    I have some questions here :
    -This implementation is to solve the issue of initialising the context with `null` (`createContext(null)) , but in (at least in this) situation, why not initialising the context with a `light` (or `dark`) value? We are supposed to pass to the create context function the initial value of our context. And our web/app , should have an initial theme mode (it should be either dark or light the moment it loads for the first time). This way there is no need to check for `null` value.
    -Why is it annoying having to pass around variable `ThemeContext` , but not function `useThemContextProvider` ?
    -If we try to use a context outside of the provider, we will have an error anyway, because the point of creating a context, is that only the components inside of the provider, have access to it. To me, is like trying to put an `useEffect` inside an If/else , React will throw an error remind us.
    Don't get me wrong, I love your approach, and how clearly and simple you explain everything (that's why I am subscribed ;) ) , but if you are saying something as radical as that we shouldn't do it in the "regular" way, for us ( beginners or juniors,) it would be good to have a bit more of explanation about it.

  • @kmylodarkstar2253
    @kmylodarkstar2253 5 месяцев назад

    I think not memoize the Ctx Provider Value could be a problem, do you?

  • @user-bi1lo8pm2l
    @user-bi1lo8pm2l 4 месяца назад +1

    really good

  • @tuffilaro1565
    @tuffilaro1565 8 месяцев назад +1

    Wow what a great tutorial. thank you for including the types part at the end aswell, really helpful! I just got a question, since you said it's better to use type instead of interface is there any use case for using interface or should you alwasy use type?

    • @ByteGrad
      @ByteGrad  8 месяцев назад

      I put up a video some time ago about "Type vs Interface" in which I take the position to always use the type alias. So far I haven't seen good use cases for interface. Maybe there are some though, there are always edge cases.

    • @daun55
      @daun55 4 месяца назад +1

      I thinks in this case its better to use enum rather than type

  • @therealsharat
    @therealsharat 5 месяцев назад

    I am not sure if you can just straight up export the state and the setstate variable in just one useContext() function.
    You are returning only context in the function, then how come when you export the function, you equate it to {state, setstate} = useStateFunction(), when your useStateFunction is returning only 1 variable and that is the context (here the required context is state))

  • @alexyap9138
    @alexyap9138 8 месяцев назад +1

    thank you! will your React/Next.js course be coming out soon?

    • @ByteGrad
      @ByteGrad  8 месяцев назад +1

      Thanks, it’s very close. Make sure you’re on the email list :)

  • @yan1ist
    @yan1ist 8 месяцев назад +1

    amazing

  • @InarusLynx
    @InarusLynx 2 месяца назад +1

    I am still very new to typescript and next.js. Your videos keep surprising me with things I've never seen anyone else mention. I've been having lots of frustration trying to solve lots of little annoyances like trying to determine the theme being used.
    Now if only you could tell me how to get the oklch color that Daisyui uses in its themes and convert them so chart.js can use them since they only use hex, rgb, or hsl.
    None of the color converters that I've looked into seems to handle oklch.

  • @arian5126
    @arian5126 8 месяцев назад +3

    You don't have to create that hook. Instead of initial "null" value, I give it an initial value for both "theme" and "setTheme" and it works that simple.

    • @justusonuoha8224
      @justusonuoha8224 8 месяцев назад +2

      I agree with you. Creating a hook just to escape null doesn’t make any sense to me.
      I use this pattern btw but not because I want to escape null. I always create contexts with valid default values.

    • @slashwhatever
      @slashwhatever 8 месяцев назад

      The more important part of the hook is throwing the error when devs try use it outside the required provider.

  • @ug1131
    @ug1131 9 месяцев назад +1

    Great content as always, thank you👏👏

  • @marusdod3685
    @marusdod3685 9 месяцев назад

    could've also added a custom error boundary in case the consoomer component was not wrapped in a Provider