Making React Context FAST!

แชร์
ฝัง
  • เผยแพร่เมื่อ 10 ก.ค. 2024
  • Let's make context as fast as any state manager out there by only using the hooks baked right into React.
    Code: github.com/jherr/fast-react-c...
    👉 Practical Module Federation Book: module-federation.myshopify.c...
    👉 No BS TS (The Book): no-bs-ts.myshopify.com/
    👉 I'm a host on the React Round-Up podcast: devchat.tv/podcasts/react-rou...
    👉 Don't forget to subscribe to this channel for more updates: bit.ly/2E7drfJ
    👉 Discord server signup: / discord
    👉 VS Code theme and font? Night Wolf [black] and JETBrains Mono
    0:00 Introduction
    0:49 Demo Application Walkthrough
    4:23 Simple useState Based Context
    10:24 Does Memoization Help?
    11:09 Creating A Ref-Based Fast Context
    24:22 Porting to useSyncExternalStore
    26:04 Adding Selector Support
    28:46 Making Fast Context Generic
    32:38 Outroduction
    #react18 #reactjs
  • วิทยาศาสตร์และเทคโนโลยี

ความคิดเห็น • 432

  • @norberthorgas2428
    @norberthorgas2428 ปีที่แล้ว +162

    I have been working with React for about 4 years and recently started teaching React to juniors. Today I feel like I am a junior again 😀 Thanks for sharing this amazing content Jack!!

  • @ljuglampa
    @ljuglampa ปีที่แล้ว +7

    I've made this "fast context" solution a few times. The thing is, you don't even need any Provider here. You can just use any external object with the same pub/sub api, since we're triggering re-renders manually, so this useStore hook can pick its store from wherever, not just from a context.
    Also, when you do useRef(new Set(...) you're re-creating this Set for every render of that custom hook. It won't care about the value but still, it's "cleaner" to do:
    if (!store.current) store.current = new Set(...)
    to make it just happen once. Otherwise awesome content Jack. I love the useSyncExternalStore abstraction to get rid of setting up local states manually. Feels safer also to have React internals take care of that part.

    • @untitleddocument4197
      @untitleddocument4197 ปีที่แล้ว

      Good point :D I guess this also means you could use a store that syncs with localstorage, if it made sense too

    • @PeerReynders
      @PeerReynders ปีที่แล้ว

      The Provider and the `useStore()` hook are fine.
      They decouple the components from the source which is useful for developer tests and for inclusion in design system guides.
      However, especially as `useSyncExternalStore` is being used, there is no need for `useStoreData()` to be a hook so it can just be implemented as a vanilla `createStore` function without all the `useRef()`and `useCallback()` complexity.
      Also since the properties in the created { set, get, subscribe } object are stable through the lifetime of the application it makes sense to just bind it to a `store` variable within the closure created by `createFastContext()` that both `createContext` and `StoreContext.Provider value` can use to eliminate the initial `null`.

  • @alexlohr7366
    @alexlohr7366 ปีที่แล้ว +84

    Small remark: if you are storing your data in a ref in any case, there is no need to overwrite it with a new object that destructures both the current data and the updates, instead use Object.assign to copy over the partial values for a little better performance. Otherwise, this is a nice pattern and you've done a great job showing how it comes together, @Jack Herrington!

    • @talatkuyuk6556
      @talatkuyuk6556 ปีที่แล้ว +2

      How ? [line-22] if I use Object assign ------> store.current = Object.assign(store.current, value); but TypeScript says (Type 'Partial' is not assignable to type 'Store')

    • @alexlohr7366
      @alexlohr7366 ปีที่แล้ว +1

      @@talatkuyuk6556 in this case, you can cast value to store. This is a shortcoming of TypeScript.

    • @talatkuyuk6556
      @talatkuyuk6556 ปีที่แล้ว

      @@alexlohr7366 Nope, I casted the value as Store; but Object.assign first parameter should extend {} in nature; TypeScript is still angry.

    • @mortezatourani7772
      @mortezatourani7772 ปีที่แล้ว

      @@talatkuyuk6556
      What about this:
      `Object.assign(store.current, value);`

    • @PeerReynders
      @PeerReynders ปีที่แล้ว +6

      @@talatkuyuk6556
      You have to constrain Store's type-note below the `Store extends Record`:
      export default function createFastContext(initialState: Store) {

      const set = useCallback((value: Partial) => {
      Object.assign(store.current, value);
      subscribers.current.forEach((callback) => callback());
      }, []);

  • @quadro201
    @quadro201 ปีที่แล้ว

    Hey man, please never stop making videos. I learn so much from you. It has been a year since I've been working full time on react apps and there hasn't been a day without something new. Thankyou.

  • @ivanabadzhiev1214
    @ivanabadzhiev1214 ปีที่แล้ว +1

    Amazing, thank you Jack for all the value you provide with your videos

  • @mysandyballs
    @mysandyballs ปีที่แล้ว +2

    Exactly what I was looking for to take context to the next level. Great work as always Jack 👍

  • @manuelpascual7063
    @manuelpascual7063 ปีที่แล้ว +1

    Jack, this is amazing content. I never thought about the idea to use this combination between context and useRef. You are such a huge inspiration 😊

  • @SergeyChebykin
    @SergeyChebykin ปีที่แล้ว +1

    Jack, thanks a lot for making really excellent educational videos! This one is especially important, given how easy it is to misuse React context and end up being deep under a lot of performance issues. Thank you!

  • @hugot8226
    @hugot8226 ปีที่แล้ว

    That's SO VALUABLE Jack ! I was looking for a solution for exactly this problem for months. What an elegant solution !

  • @MrChernicharo
    @MrChernicharo ปีที่แล้ว

    Woooah! I couldn't stress enough how much I loved this video! Thank you Jack! 🥳

  • @KPOPYakuzaz
    @KPOPYakuzaz ปีที่แล้ว +2

    Great content as usual, it's really hard to find react content at this level so it's highly appreciated. Great pattern, love the use of refs for this

  • @tusharrai3644
    @tusharrai3644 ปีที่แล้ว +1

    Very sturdy implementation, just loved the approach and the way you explained. can't wait to Implement this fast context.

  • @riman8493
    @riman8493 ปีที่แล้ว +1

    This was quite amazing and answers a pretty real need I actually have right now. Thank you _so much_ for putting this out there!

  • @josephizang6187
    @josephizang6187 ปีที่แล้ว +15

    Thank you Jack, the time you take to make your content..with so much thought and care makes every video a gem. Again, thank you.

  • @clouatre3034
    @clouatre3034 ปีที่แล้ว +2

    It's incredible how much I have learned from you. Thank you once again!

  • @parsanasirimehr7267
    @parsanasirimehr7267 ปีที่แล้ว +2

    I love it when these type of ideas come along. I wouldn't use it for state management, but it has a lot of potential when it comes to Multilayer contexts that I deal with at work. It piles up little by little. Thanks Jack

  • @mikeks81
    @mikeks81 ปีที่แล้ว +1

    Really slick! Adopting this pattern immediately. Thanks for sharing!

  • @creatorsremose
    @creatorsremose ปีที่แล้ว +5

    Jack, it's like you're following my work and post videos that are surgically relevant to my challenges. You're so awesome. Thank you so much.

  • @axe-z8316
    @axe-z8316 ปีที่แล้ว +2

    Hey long time interested, but now full fledged fan, this is hands down your best stuff to date. Amazing

  • @igrb
    @igrb ปีที่แล้ว +2

    This was so instructive, I love how you teach not only these cool patterns but the reasoning behind them AND colol little details like the Partial there.
    Thanks Jack!

  • @matt35953
    @matt35953 ปีที่แล้ว +2

    Jack, you a a legend! Spent most of yesterday looking at state mangers to address this kind of issue... glad I took a "TH-cam break."

  • @1235niki
    @1235niki ปีที่แล้ว +2

    Thanks for sharing this new pattern Jack. Really helpful.

  • @scottsmith416
    @scottsmith416 8 หลายเดือนก่อน +2

    I've been looking for a solution like this for years! Thanks, Jack!

  • @MajdBaddour
    @MajdBaddour ปีที่แล้ว +3

    A superb solution, refactored to perfection. That was an excellent video, as always. Thank you Jack for all you do.

  • @frostmichael8360
    @frostmichael8360 ปีที่แล้ว +1

    It's a rainy and windy sunday, i drink a cup of tea and i'm definitly fallen in love with your code and conception. Thank you !

  • @cristiang4774
    @cristiang4774 ปีที่แล้ว +3

    This tutorial blew my mind (in a positive way). Amazing stuff!

  • @shiyaamcodes7428
    @shiyaamcodes7428 10 หลายเดือนก่อน

    I was looking for this exact thing for the past two days!!!! Glad I found this

  • @shivamjhaa
    @shivamjhaa ปีที่แล้ว +1

    At this point, I don't really know how you keep coming up with a new cooler video. Thanks, from India

  • @bushigi5913
    @bushigi5913 ปีที่แล้ว +2

    What kind of solution is this!! You just made my understanding of react to another level! Thank you so much, I'll definitely come back to watch this video again and again.

  • @talatkuyuk6556
    @talatkuyuk6556 ปีที่แล้ว +1

    Your solution is awesome; you are great guy to explain this kind of structural videos, thanks again.

  • @BlurryBit
    @BlurryBit ปีที่แล้ว +2

    Lovely video! Concise, and very helpful!! Thank you Jack :)

  • @lilpodbebe
    @lilpodbebe ปีที่แล้ว +2

    Brilliant! I need this to maintain a complex form without a complete rewrite. Thank you! 🤩

  • @monastyrskiiden
    @monastyrskiiden ปีที่แล้ว +5

    What a wonderful explanation, I've been working with React for over 4 years already, and still, there's something new I get to discover every day.

  • @Bookwala12
    @Bookwala12 ปีที่แล้ว

    Woah Jack, you are a magician and even after watching you so much, I still can’t wrap my head over some of your concepts.. humbling experience this video was.. I will come to it again a little later in life..

  • @javLG
    @javLG ปีที่แล้ว +1

    Thanks for this implementation, you're a beast Jack!

  • @wonjunjang3839
    @wonjunjang3839 ปีที่แล้ว +3

    This is so high-quality as a junior frontend dev your contents are really helping me write neat-codes,

  • @robwatson826
    @robwatson826 ปีที่แล้ว +1

    That pub/sub solution is great! I'm relatively new to React and hadn't considered that as a way to manage state "globally" and only re-render components that need to.
    Thanks for sharing this Jack

  • @alanrice9935
    @alanrice9935 ปีที่แล้ว +1

    Great explanation, I've been toying around with using this context pattern and you explained some parts that I couldn't figure out

  • @useeffect
    @useeffect ปีที่แล้ว +1

    Thank you Jack for really valuable React.js content on TH-cam !

  • @b3ncr0w
    @b3ncr0w ปีที่แล้ว +1

    That's exactly what I was looking for! Thank you so much : )

  • @corndoggydogdog
    @corndoggydogdog 10 หลายเดือนก่อน +1

    This is smashing, thank you so much Jack! 🔥🔥🔥🔥

  • @vakhtangnodadze4802
    @vakhtangnodadze4802 ปีที่แล้ว +4

    Awesome video Jack. Your videos are like goldmines.

  • @nathanfranck5822
    @nathanfranck5822 ปีที่แล้ว +6

    Jack writing a solid library in real-time is just incredible. Love to see it and super empowering for anyone looking in to see that you don't need 100 npm packages in your project to make something super solid and robust!
    The more code that you can own and understand yourself now means more flexibility and creativity later as you figure out what your project is and can be. Also helps even if you're using pre-built libraries to explore in code yourself to know exactly what you want out of a library and cut through all the bullshit you don't need.

  • @sissipwns
    @sissipwns ปีที่แล้ว +1

    Omg just realizing that context is initially designed for slow-changing-stuff really enhanced my mental model of React. Thanks so much for your videos, you are the coding buddy I don't have :)

  • @mikexcoder1508
    @mikexcoder1508 ปีที่แล้ว +1

    came here from Codecamp, awesome content. Subbed!

  • @DIN_A8
    @DIN_A8 ปีที่แล้ว +1

    I never get tired of the view, what a zen-place to work from

  • @Chrosam
    @Chrosam ปีที่แล้ว +2

    I haven't seen the video yet, but based on previous videos I know it's gonna be amazing.
    I like that you don't only show HOW to do it, but WHY you do it.
    Here, you dropped this, king 👑

    • @Chrosam
      @Chrosam ปีที่แล้ว

      Done, yep, as expected, never fails to amaze.

  • @lorenzotomasdiez3325
    @lorenzotomasdiez3325 ปีที่แล้ว

    I just found out about your channel and it is impressive the way you explain. It's amazing.

  • @zachatack21
    @zachatack21 3 หลายเดือนก่อน +1

    This is an absolutely incredible tutorial! I learned a ton from this! I understand context, useRefs, and how components rerender SO much better now! Thank you!!!

  • @OleksandrDanylchenko2k
    @OleksandrDanylchenko2k ปีที่แล้ว +1

    Thanks 🙏
    It's the clearest tutorial on how to implement the fast context

  • @igogs7095
    @igogs7095 ปีที่แล้ว +7

    Such a great lesson! This channel is diamond for ones who wanna become really good at react! Awesome job, thank you!

  • @ozgursar5386
    @ozgursar5386 11 หลายเดือนก่อน +1

    This tutorial is simply amazing. Thank you!

  • @arogueotaku
    @arogueotaku ปีที่แล้ว

    This has to be one of the best react videos I have watched. +1 Subscriber

  • @nikolagospodinov9057
    @nikolagospodinov9057 ปีที่แล้ว +82

    Jack, thank you for all your videos! Thanks to you I leveled up my skills and got to a senior position! I hope you come out with a course soon describing all of the mid/advanced React concepts, best practices, project structuring, when and how to use 3rd party libraries like RQ, state management, and all those good stuff. I would literally pay anything for that!

    • @jherr
      @jherr  ปีที่แล้ว +23

      'Anything'? I can imagine? th-cam.com/video/rZBHits8JPI/w-d-xo.html

    • @quelchx
      @quelchx ปีที่แล้ว +4

      React Query as some excellent documentation -- dedicate a day to browse through it and you will be surprised what you will be able to accomplish with that library. My companies application has some complicated state between the server and client and react query has made it so easy to manage state, handle mutations + hydrating the client. It only took me a few days of going through the documentation and now I feel fluent with talking to that library -- it shouldn't take you very long if you dedicate a few hours to it.

    • @jherr
      @jherr  ปีที่แล้ว +7

      @@quelchx th-cam.com/video/JaM2rExmmqs/w-d-xo.html

    • @quelchx
      @quelchx ปีที่แล้ว +6

      @@jherr I have watched this video =). When I first used RQ I thought it was more for data fetching and managing it's state but I have used it to simply manage state from one component to another and mutate that state. I love RQ it's such a useful tool.
      Honestly Jack I have learned a lot through your content and have taken patterns you have provided and I use them daily =).

    • @jherr
      @jherr  ปีที่แล้ว +1

      @@quelchx Thank you so much!

  • @codebycarlos
    @codebycarlos ปีที่แล้ว +1

    This is incredibly helpful. Thank you!

  • @rohitjha7202
    @rohitjha7202 ปีที่แล้ว

    Thank you so much, Jack, I have tested it, and it works great, Definitely I will use this in my production-level app.

  • @avneet12284
    @avneet12284 ปีที่แล้ว +1

    Brilliant stuff, Jack !

  • @mortezatourani7772
    @mortezatourani7772 ปีที่แล้ว +19

    Let's make react context great again :)
    I think the actual implementation of context should be something like this and the current version is really deficient.
    And again really enjoyed the way you went step by step, improved the solution, and made it generic. It not only helps with understanding the process but also demonstrates how to eat an elephant.
    Thanks again.

  • @agk2011
    @agk2011 ปีที่แล้ว +1

    Thank you so much for such an amazing video.
    This type of content is really inspiring.

  • @ynonshoshan
    @ynonshoshan ปีที่แล้ว +1

    That was bloody amazing

  • @beemanik
    @beemanik ปีที่แล้ว +1

    My first comment to you. Your videos is super useful and straightforward. I like using Redux, but Context is super for local high state around piece of tree. I wish you GL and thanks for sharing your experience .

  • @JhonLavigne
    @JhonLavigne ปีที่แล้ว +1

    Jack, this is by far the most interesting video about state management in React that I have ever seen. Holy shit, Sir. you are a Beast.

  • @motivateme2402
    @motivateme2402 ปีที่แล้ว +1

    Thank you Jack for the best content I've ever seen, you're a great and awesome guy, and You thought me a lot

  • @fahmijabbar1595
    @fahmijabbar1595 ปีที่แล้ว +1

    Absolute meat!!! Thank you for the tutorial Jack

  • @ynonshoshan
    @ynonshoshan ปีที่แล้ว +2

    in my eyes this should be an essential upgrade to react and should be an available hook that comes right out of the box, thanks for this!

  • @BNakato
    @BNakato ปีที่แล้ว +2

    Great stuff.. love these kind of videos

  • @DEVDerr
    @DEVDerr ปีที่แล้ว +16

    You have almost introduced fine-grained reactivity to React like it is for Solid and Svelte. Fantastic job 🔥
    Wondering why React did not yet implement such a thing lol

  • @Kwuala
    @Kwuala ปีที่แล้ว +1

    Amazing video, thank you Jack !

  • @marlonmarcello
    @marlonmarcello ปีที่แล้ว +3

    Love your content Jack, thanks for this great explanation! I am a React dev, I work with it every day, and this kinda of hassle that we have to go through to get this level of performance is one of my biggest pet peeves with the framework. For my freelance projects I use Svelte and I get all of that for free, it's glorious. Looking forward to a video on the new upcoming SvelteKit!

  • @MsPrakhar12
    @MsPrakhar12 10 หลายเดือนก่อน

    Very very cool approach. Loved it. ❤

  • @shin5302
    @shin5302 ปีที่แล้ว

    Thank you, Jack! for your amazing content. It helps me a lot.

  • @quelchx
    @quelchx ปีที่แล้ว +29

    Using React Context and patterns like what you have shown too me is more than enough for a bunch of use cases. I'm glad to see a video like this so I can point some of our developers we hire to this video to get a gist of what I call baked into React for global state management using HOC patterns.
    Im sure I'm not alone with feeling like this but once you learn a few state management patterns/libraries (Zustand, Jotai, React Query, Redux, React Context patterns) I enjoy using almost all of them and when it comes to making a choice on which one to use I often struggle to make a choice because they are all great IMO (for React apps)
    Thanks again for all the content you provide to the React Ecosystem it's great, absolutely love the content -- your a great guy for all the work you provide towards developers coming into this gig.

  • @nparashar150
    @nparashar150 ปีที่แล้ว +1

    Thanks for sharing another great video sir!!

  • @miguelblanco5563
    @miguelblanco5563 ปีที่แล้ว

    This is pretty awesome, I just implemented this on my work

  • @skandertebourbi357
    @skandertebourbi357 ปีที่แล้ว +1

    Thank you for this amazing content, really insightful.

  • @AlJey007
    @AlJey007 ปีที่แล้ว +1

    I was playing around with your code and came to a realization that the magic is entirely in the useSyncExternalStore method and the context is 100% superfluous, it is not doing anything at all. In fact, useRef and useCallback are also redundant.
    With a few tiny tweaks this useful code became a game changer for me.
    Thank you for this video!

  • @patrykkalinowski6979
    @patrykkalinowski6979 5 หลายเดือนก่อน +1

    It was really good. Thanks a lot !

  • @usamaimran1516
    @usamaimran1516 ปีที่แล้ว

    Simply one of the smartest solution. Thumbs up ✌️👌👌

  • @coldboyvic
    @coldboyvic 6 หลายเดือนก่อน

    This is one of the best tutorials on TH-cam 🙌💯

  • @loia5tqd001
    @loia5tqd001 ปีที่แล้ว +6

    I'm really interested in seeing how this would get involved in a more complex application, please do so Jack.
    For example:
    - involving async actions
    - actions that need states from different stores or fields of store

  • @zlackbiro
    @zlackbiro ปีที่แล้ว +4

    This is the most insane video you made. This should be on npm as a library. 😁

  • @MuhammadAdnan-nj4it
    @MuhammadAdnan-nj4it ปีที่แล้ว +1

    good work king, love you

  • @fotoflo
    @fotoflo ปีที่แล้ว +1

    Thanks Jack! Came for the context, stayed for the typescript!

  • @somewonderfulguy
    @somewonderfulguy 3 หลายเดือนก่อน

    I really love this combo. I'm going to use fast context in UI kit I develop (for fun and practice) as I see it reasonable to use React context instead of any 3rd party state management. Less dependencies better for UI kit.
    I made one modification, inside Provider component there are two providers now - one provides 'set', the other 'get' and 'subscribe'.
    And instead of useStore there are useStoreValue and useStoreDispatch now.
    There are cases when you have store setter that does not care about value, so component that uses setStore will never re-render as 'set' is always stable.
    Thanks for the video and solution it is awesome!

  • @hikarukun5126
    @hikarukun5126 ปีที่แล้ว +1

    The only part I didn't understand was a pub/sub model and how it works, maybe because I have never used it before. I believe I will watch this episode a few more times and read articles about how this pattern works. Thanks a lot for such majestic content, I appreciate it as other fellows here.

  • @user-mw6ny9xy4r
    @user-mw6ny9xy4r ปีที่แล้ว +1

    Thank you Jack, I really love this content I`m going to adjust this on my toy project now awsome!

  • @MukulDuttshades
    @MukulDuttshades ปีที่แล้ว

    ReturnType was clever.

  • @fadfooood
    @fadfooood ปีที่แล้ว +1

    I will never do that but hey Jack now I understand what Zustand and other state managers do at a scale. Thanks!

  • @AZioPb
    @AZioPb ปีที่แล้ว +1

    Great stuff! Thank you.

  • @martingunduz6911
    @martingunduz6911 ปีที่แล้ว +1

    This is soooo goood!

  • @shashikantmarskole
    @shashikantmarskole ปีที่แล้ว

    Thank you jack, for React quality content and learn new from it. thank you

  • @estebanmunchjones7946
    @estebanmunchjones7946 ปีที่แล้ว +1

    thanks a lot Jack, you'r a legend!

  • @mrasoahaingo
    @mrasoahaingo ปีที่แล้ว +6

    I really love the way you explain concept by doing step by step. It reminds me of Dan Abramov trying to re implement Redux from scratch. It make things clearer and straightforward.
    Really really enjoy your video format! Thanks!

  • @cintron3d
    @cintron3d ปีที่แล้ว +2

    This is brilliant, thank you!

    • @jherr
      @jherr  ปีที่แล้ว +2

      Thank you so much!

  • @VKD007
    @VKD007 ปีที่แล้ว

    Amazing man, as always.

  • @raulcasari5250
    @raulcasari5250 ปีที่แล้ว +1

    Awesome, thanks for your videos

  • @nhulongctk10
    @nhulongctk10 10 หลายเดือนก่อน +1

    Your content is amazing

  • @TheOllieJT
    @TheOllieJT ปีที่แล้ว +1

    Love ot, more advanced content like this please!

  • @kelvinklee
    @kelvinklee ปีที่แล้ว +4

    This is pretty awesome, I am curious how close a small lib like Zustand is basically just this general structure with a few more features? Good to see what's going on behind the scenes. Thanks for always sharing amazing content!

  • @ofirfridman5829
    @ofirfridman5829 ปีที่แล้ว +1

    Wow this is amazing :) Thanks