Why use a Custom Hook for React Context API instead of useContext (+ TypeScript)

👉 NEW React & Next.js Course: bytegrad.com/courses/professi...
Hi, I'm Wesley. I'm a brand ambassador for Kinde (paid sponsorship).
👉 Add authentication to your app FAST: bit.ly/3QOe1Bh
👉 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

Пікірлер: 195

  • @ByteGrad
    @ByteGrad4 ай бұрын

    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
    @revillsimon10 ай бұрын

    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

    10 ай бұрын

    I appreciate that!

  • @noobgam6331

    @noobgam6331

    9 ай бұрын

    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

    9 ай бұрын

    ⁠@@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

    9 ай бұрын

    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
    @youneshenni541710 ай бұрын

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

  • @martapfahl940
    @martapfahl94010 ай бұрын

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

  • @krsnamara
    @krsnamara5 ай бұрын

    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.

  • @laputafelix
    @laputafelix10 ай бұрын

    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.

  • @n8guy
    @n8guy4 ай бұрын

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

  • @shreyasvaidya9552
    @shreyasvaidya955210 ай бұрын

    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.

  • @rayaqin
    @rayaqin6 ай бұрын

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

  • @JoeyMa
    @JoeyMa9 ай бұрын

    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!

  • @chrisauret3785
    @chrisauret37859 ай бұрын

    +10 for showing how to implement the typescript version thoroughly

  • @maykefernandesdossantos7374
    @maykefernandesdossantos737410 ай бұрын

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

  • @lillenk125
    @lillenk12510 ай бұрын

    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!

  • @njahncke
    @njahncke9 ай бұрын

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

  • @LeonardoJaquesDev
    @LeonardoJaquesDev7 ай бұрын

    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

  • @UmeshKumar-mt2dp
    @UmeshKumar-mt2dp5 ай бұрын

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

  • @Xe054
    @Xe0549 ай бұрын

    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!

  • @ekanemeno4565
    @ekanemeno45658 ай бұрын

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

  • @bdeink
    @bdeink2 ай бұрын

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

  • @VLADICA94KG
    @VLADICA94KG10 ай бұрын

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

  • @ByteGrad

    @ByteGrad

    10 ай бұрын

    Thanks, will do!

  • @faroukdourmane7632
    @faroukdourmane76329 ай бұрын

    Perfect explanation, Thanks !

  • @andrewraj3846
    @andrewraj384610 ай бұрын

    Nice and very informative. Can you speak louder

  • @ByteGrad

    @ByteGrad

    10 ай бұрын

    Thanks, will do

  • @abbaskareem5281
    @abbaskareem528110 ай бұрын

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

  • @flameofheartsflameofhearts3955
    @flameofheartsflameofhearts39556 ай бұрын

    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 🙏

  • @nicolascuor2378
    @nicolascuor23788 ай бұрын

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

  • @6th.player
    @6th.player8 ай бұрын

    I got hooked! thanks man!

  • @thompsaa
    @thompsaa7 ай бұрын

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

  • @Clem.E
    @Clem.E10 ай бұрын

    Incredibly clear video. Thank you very much.

  • @scherschak
    @scherschak4 ай бұрын

    Thanks a lot! Super easy to understand

  • @SohibjonAbdialimov
    @SohibjonAbdialimov7 ай бұрын

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

  • @apuravela
    @apuravela6 ай бұрын

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

  • @nicolamigone8849
    @nicolamigone884910 ай бұрын

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

  • @zhenglaowang8489
    @zhenglaowang84899 ай бұрын

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

  • @zackarybrumfield2
    @zackarybrumfield28 ай бұрын

    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

    7 ай бұрын

    yup very Few Videos are there related to Context in null

  • @datasagedev
    @datasagedev6 ай бұрын

    Thank you, very well explained and easy to grasp.

  • @ivandamyanov
    @ivandamyanov10 ай бұрын

    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!

  • @MrColins710
    @MrColins710Ай бұрын

    good explanation, thank you! everything is clear

  • @acloudonthebluestsky9687
    @acloudonthebluestsky96877 ай бұрын

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

  • @Miguel-em2yj
    @Miguel-em2yj10 ай бұрын

    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

    10 ай бұрын

    Thank you! Will do!

  • @victorumeh3768
    @victorumeh376810 ай бұрын

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

  • @Alessandro-nq3tm
    @Alessandro-nq3tm10 ай бұрын

    As a web dev, great content! Subscribed!

  • @cosmo-rodrigues
    @cosmo-rodrigues5 ай бұрын

    What a class, man. What a class!

  • @throwaway-lo4zw
    @throwaway-lo4zw4 ай бұрын

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

  • @meka4996
    @meka49969 ай бұрын

    You are the TypeScript man! Thanks

  • @musiuralamopu9589
    @musiuralamopu95895 ай бұрын

    Very useful and easy to catch the concept

  • @jhonnynasc
    @jhonnynasc8 ай бұрын

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

  • @odanabunaga2505
    @odanabunaga25059 ай бұрын

    superuseful, thanks!

  • @UwU-dx5hu
    @UwU-dx5hu4 ай бұрын

    Thank you so much❤

  • @mikro_rimoslav
    @mikro_rimoslav4 ай бұрын

    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.

  • @zivtamary
    @zivtamary10 ай бұрын

    thanks :) made my contexts a lot cleaner

  • @austincodes
    @austincodes10 ай бұрын

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

  • @yusufkaymaz647
    @yusufkaymaz6478 ай бұрын

    great video thank you :)

  • @franklinantony
    @franklinantony10 ай бұрын

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

  • @victorduarte4059
    @victorduarte40598 ай бұрын

    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...

  • @7doors847
    @7doors84710 ай бұрын

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

  • @lemondigitaldesign
    @lemondigitaldesign7 ай бұрын

    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!

  • @builtdifferent3350
    @builtdifferent335010 ай бұрын

    Glad I found your channel

  • @hbela1000
    @hbela10005 ай бұрын

    crystal clear.

  • @riteshkc814
    @riteshkc8145 ай бұрын

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

  • @fabianpetersen2452
    @fabianpetersen24526 ай бұрын

    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?

  • @SSango-hk9sm
    @SSango-hk9sm8 ай бұрын

    duuuuude!!!!!you got my sub!

  • @abdelfadeel0
    @abdelfadeel06 ай бұрын

    great explanation ❤

  • @victorsaisse1340
    @victorsaisse134010 ай бұрын

    that was an awesome explanation

  • @snivels
    @snivels10 ай бұрын

    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

    10 ай бұрын

    Thanks a lot, appreciate it

  • @hugopinho9534
    @hugopinho95347 ай бұрын

    Amazing!!

  • @Ali-ei3mg
    @Ali-ei3mg10 ай бұрын

    Thanks I learn a alot from this video

  • @Its-InderjeetSinghGill
    @Its-InderjeetSinghGill5 ай бұрын

    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
    @nogafouz21748 ай бұрын

    good video thanks

  • @Fanaro
    @Fanaro9 ай бұрын

    Looking forward to your React course!

  • @ByteGrad

    @ByteGrad

    9 ай бұрын

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

  • @yashdubeyofficial
    @yashdubeyofficial9 ай бұрын

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

  • @Yobo77
    @Yobo7710 ай бұрын

    Great explanation! Nice job! 🙂

  • @ByteGrad

    @ByteGrad

    10 ай бұрын

    Thank you! 😃

  • @nilkanthpatadiya9524
    @nilkanthpatadiya95249 ай бұрын

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

  • @alejandroyanes391
    @alejandroyanes3919 ай бұрын

    amazing !

  • @MuhammadHaseebAhmed
    @MuhammadHaseebAhmed10 ай бұрын

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

  • @Mitsunee_
    @Mitsunee_10 ай бұрын

    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.

  • @haniseanda
    @haniseanda10 ай бұрын

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

  • @erce_
    @erce_10 ай бұрын

    Good stuff, thanks

  • @pagarevijayy
    @pagarevijayy4 ай бұрын

    👍 wonderful video

  • @salvadorbalas5234
    @salvadorbalas523410 ай бұрын

    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!

  • @MrZiyak99
    @MrZiyak9910 ай бұрын

    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?

  • @tahamanna3600
    @tahamanna36005 ай бұрын

    great video

  • @Assassin29
    @Assassin294 ай бұрын

    Great info. Which theme are you using in vscode?

  • @balduin_b4334
    @balduin_b433410 ай бұрын

    great video!

  • @user-bi1lo8pm2l
    @user-bi1lo8pm2l5 ай бұрын

    really good

  • @tuffilaro1565
    @tuffilaro15659 ай бұрын

    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

    9 ай бұрын

    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

    5 ай бұрын

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

  • @vanijatkosolomichev9452
    @vanijatkosolomichev94524 ай бұрын

    Smart... 👌

  • @RolandAyala
    @RolandAyala10 ай бұрын

    @5:21. Curious why `React.useContext` to `useContext` is a great co-pilot suggestion. I prefer more explicit style -- what's the con (other than needing to type more letters if multiple useContext references, which wasn't the case here)? Great video btw -- like your style (direct, nice pace). Thanks!

  • @nurudeenyekeen9292

    @nurudeenyekeen9292

    10 ай бұрын

    Copilot is an AI model based on some data set, most likely that's what alot of the repos used

  • @AmodeusR
    @AmodeusR10 ай бұрын

    My gosh, you just showed live the type hell I hate when it comes to typescript, and I suffered a lot because of that xD It's interesting to see someone solving all of those typescript complaints, and that easy?! I hope to be like you one day :']

  • @ByteGrad

    @ByteGrad

    10 ай бұрын

    Haha I was like this at some point too

  • @krisbude9607

    @krisbude9607

    10 ай бұрын

    One day you will realise hopefully :) Everyone goes to this stage at first.

  • @benfoster5752
    @benfoster57529 күн бұрын

    How would you propose seeding the context with initial state from a parent layout page?

  • @AngrejKumar
    @AngrejKumar5 ай бұрын

    Nice

  • @ug1131
    @ug113110 ай бұрын

    Great content as always, thank you👏👏

  • @thaifred
    @thaifred8 ай бұрын

    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
    @darkwoodmovies9 ай бұрын

    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

  • @gabrielokundaye1502
    @gabrielokundaye150210 ай бұрын

    Great!

  • @hey.............
    @hey.............10 ай бұрын

    This content is gold. Thanks for sharing it. 🙌

  • @InarusLynx
    @InarusLynx3 ай бұрын

    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.

  • @brkdnmz99
    @brkdnmz9910 ай бұрын

    Thanks for the video! Would you prefer not extracting the type "dark" | "light" as a separate type Theme, and instead use ThemeContext["theme"] as theme's type? Then, we can use ThemeContext["theme"] wherever Theme is used. However, your way seems cleaner.

  • @QwDragon

    @QwDragon

    10 ай бұрын

    Won't work as you need it for setTheme too.

  • @brkdnmz99

    @brkdnmz99

    10 ай бұрын

    @@QwDragon I actually tried it beforehand, and it works if you use the type itself inside its definition, and even what I wrote works: ThemeContext["theme"]. So, it turns out you can use another property to define some property's type.

  • @alexyap9138
    @alexyap91389 ай бұрын

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

  • @ByteGrad

    @ByteGrad

    9 ай бұрын

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

  • @yan1ist
    @yan1ist10 ай бұрын

    amazing

  • @Fanaro
    @Fanaro9 ай бұрын

    This video is a great demonstration of why React overcomplicates things, often. This shouldn't be this much work...