Mastering React Batch Updating

2024 ж. 2 Мам.
43 321 Рет қаралды

Turns out useState might not be as simple as you think, and calling the set state function at the wrong time might result in React not batching state updates and might hurt your performance or cause bugs. Let's dig deep into this and figure out when React batches updates, when it doesn't and how to fix that.
👉 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 Operator Mono
👉 Terminal Theme and font? oh-my-posh with powerlevel10k_rainbow and SpaceMono NF
0:00 Introduction
1:37 Going Asynchronous
4:19 Fixing The Bug
5:49 Batching Updates in React 16 & 17
6:28 Upgrading To React 18
8:16 Fixing The App The Right Way
9:55 Outroduction
#react #batch_updates

Пікірлер
  • Thanks jack. You’re one of the few educators who are remarkably good at what they do. Your tutorials are really helping me in relearning react after 2 years.

    @saudqureshi3716@saudqureshi37162 жыл бұрын
  • Awesome tutorial Jack. Thank you so much for sharing!

    @zhuolintsai9030@zhuolintsai90302 жыл бұрын
  • It is not easy to find this kind of in depth explorations around and get benefit out of true experiences like yours. Huge respect and thanks for sharing with us Jack.

    @EnesKab@EnesKab2 жыл бұрын
  • This channel is the best thing I've found in a long time! I'm so grateful!

    @ElvenIvy07@ElvenIvy07 Жыл бұрын
  • amazing, it very simple to understand. Please update video like this. Thank you so much for your hardwork

    @haquocviet9253@haquocviet92532 жыл бұрын
  • Thank you again. Short and in-depth video.

    @KevinOfSteel@KevinOfSteel2 жыл бұрын
  • Thank you Jack for such wonderful insights and tricks

    @SushilKumar-ig8ls@SushilKumar-ig8ls2 жыл бұрын
  • Your tutorial about React is very interesting. Thank you Jack.

    @juhandvan@juhandvan2 жыл бұрын
  • Much better topic than circling around 25 state management solutions ! loved it

    @axe-z8316@axe-z83162 жыл бұрын
  • That's some good sauce! Kudos to you sir!

    @kassios@kassios2 жыл бұрын
  • Excellent explanation Jack, thanks a lot!

    @RandomMcLain@RandomMcLain Жыл бұрын
  • Thank you for the videos, amazing content 🙏

    @danielcastro2362@danielcastro23622 жыл бұрын
  • Another great video, learned so much from watching your videos Jack. Keep it up!

    @delvv81@delvv812 жыл бұрын
  • Excellent topic that I think many people overlook! Thanks for the informative video :)

    @BarryMichaelDoyle@BarryMichaelDoyle2 жыл бұрын
  • Thank you Jack for all this good content. I'm a medior freelance front-end developer and this content is really helping me stepping up my game. It's making me feel more comfortable doing my job.

    @KerimWillem@KerimWillem2 жыл бұрын
  • Thank you Jack. Love this.

    @davidkezi6086@davidkezi60862 жыл бұрын
  • Thanks Jack, Awesome content 👍🏻

    @AbdelhameedG@AbdelhameedG2 жыл бұрын
  • I feel so lucky that I've found this channel!

    @ajgubi19@ajgubi19 Жыл бұрын
  • Thanks Jack! 🙏🏻

    @fadfooood@fadfooood2 жыл бұрын
  • I learned something new, thanks Jack!

    @master_lionel@master_lionel2 жыл бұрын
  • This channel is gold

    @rodrigomoura2108@rodrigomoura2108 Жыл бұрын
  • Unique content and always Awesome

    @usamasaleem5624@usamasaleem5624 Жыл бұрын
  • Accidentally land on a one the best video . Great Explanation

    @talhayousaf3918@talhayousaf3918 Жыл бұрын
  • Thanks for cool stuff!

    @user-ow1ji4le4k@user-ow1ji4le4k2 жыл бұрын
  • thanks man .... seriously, thank you very much for the vid

    @wisdomcube7789@wisdomcube77892 жыл бұрын
  • Awesome jack.. thanks

    @sagarreddy7461@sagarreddy74612 жыл бұрын
  • You have an amazing home in the middle of nowhere. You are becoming my inspiration

    @AbhiShek-lb8hl@AbhiShek-lb8hl Жыл бұрын
  • Thank you!

    @Y2hlc3Rlcg@Y2hlc3Rlcg2 жыл бұрын
  • Another nice video, thanks jack

    @ryank9719@ryank97192 жыл бұрын
  • Awesome content 👍🏻

    @rohitghodeswar11@rohitghodeswar112 жыл бұрын
  • You the man, Jack!

    @Colstonewall@Colstonewall2 жыл бұрын
  • Good job!

    @sea-lucky7143@sea-lucky71432 жыл бұрын
  • Thanks!! I didn't know this

    @madtin@madtin2 жыл бұрын
  • Thanks for everything Jack. You go above and beyond for your supporters and we appreciate it immensely.

    @rjmunt@rjmunt2 жыл бұрын
    • + 1

      @matthew1106@matthew11062 жыл бұрын
    • +1

      @christopherfajardo5792@christopherfajardo57922 жыл бұрын
  • Cool tut tips, really don't know such mechanism

    @havefun5519@havefun55199 ай бұрын
  • One thing that I notice, even with React 18, is that if you place a setState before a promise, it will not batch update all the states. It will batch update all the states until finding a promise, when it finds one, it's going to update all the states until that point, then it's going to search for another promise and do the same process. This was not describe in the React Docs but it makes a lot of sense, otherwise we wouldn't be able to update a loading state when doing async request without having to add the flushSync for all cases, making it pretty hard for applications to upgrade to React 18.

    @othecos@othecos Жыл бұрын
    • Can you provide a small sample demonstration in a codesandbox. I’d love to experiment more with it and if I make content out of that I’ll cite you and your example.

      @jherr@jherr Жыл бұрын
    • @@othecos Awesome, I see what you mean. And I'll definitely do a video on this and city your example because it is a good way to show it so I appreciate that. Though, IMHO, if the proper operation of the application relies on batching semantics I think that's too fragile.

      @jherr@jherr Жыл бұрын
  • You deserve an award

    @nullcheque@nullcheque2 жыл бұрын
  • hmmm was not aware of unstable batch state updates. I used to go for usereduer as usestate is nothing but a wrapper over userreducer. but this keeps code more declarative i feel. thanks.

    @technikhil314@technikhil3142 жыл бұрын
  • Awesome

    @tejasnikam3287@tejasnikam32872 жыл бұрын
  • How you edit your videos, its sooo clean and clear

    @MereDaddyJi@MereDaddyJi Жыл бұрын
  • Thanks for this! Just a request, can you please make a video on memoization in React? Like when to use React.memo, useMemo, & useCallback?

    @krishgarg2806@krishgarg28062 жыл бұрын
    • Great idea!

      @jherr@jherr2 жыл бұрын
    • +1 for this. Would love to see in depth video on these.

      @EnesKab@EnesKab2 жыл бұрын
    • @@EnesKab Don't worry, I gotcha covered. :)

      @jherr@jherr2 жыл бұрын
    • @@jherr Awesome !! Looking forward to ☺️

      @EnesKab@EnesKab2 жыл бұрын
  • Great explanation, Jack! I always group state when they are related and now I know why 😅 You mentioned that not all apps will be compatible with react 18. They are dropping support for some core feature? Migrate from 16 to 17 was not that hard. Should we expect something different for 18v ? Thank you! Great content as always!

    @victorseara9970@victorseara99702 жыл бұрын
    • The rendering engine changes to "concurrent rendering" which will break some apps if they used refs in particular ways. I did a video on it a while back.

      @jherr@jherr2 жыл бұрын
    • @Jack Herrington do you remember which video was? I'm curious to watch it and failed miserably trying to find it. Sorry to bother you.

      @victorseara9970@victorseara99702 жыл бұрын
    • @@victorseara9970 Wow, it's an old one: kzhead.info/sun/adCke7dugGKhfoU/bejne.html

      @jherr@jherr2 жыл бұрын
  • Thanks, video is great. But font is a little harder to read than regular one

    @kirylchetyrbak6542@kirylchetyrbak65422 жыл бұрын
  • Great vid Jack! I’m curious, what software do you use for onscreen drawing?

    @balzale@balzale2 жыл бұрын
    • I use ScreenBrush and a cheapy Gaomon tablet. Turns out the Gaomon is more stable than Wacom. The Wacom tablet driver software would routinely take down my Mac. The Gaomon tablet doesn't even have a driver. :) So that's a big plus.

      @jherr@jherr2 жыл бұрын
    • ​@@jherr Would you mind give a name of the specific model?

      @Merchance@Merchance2 жыл бұрын
    • That advice will call you one... million.... dollars. www.amazon.com/gp/product/B07YFG742J Oh, crap, I just pasted the link. Drat! Foiled again!

      @jherr@jherr2 жыл бұрын
  • 잭 형 사랑해요~

    @ryosukekureha4873@ryosukekureha48732 жыл бұрын
  • Hi Jack, what is the difference between flushSync (React 18) and unstable_batchedupdates (React 16~17), I read a little documentation, these two feel so similar.

    @rockmot@rockmot Жыл бұрын
  • great video as usual 😁 anybody knows the name of the VSCODE theme color he uses? 🤔

    @micheledibe@micheledibe2 жыл бұрын
    • Night Wolf [dark] with Operator Mono.

      @jherr@jherr2 жыл бұрын
  • Thank you. nice video. I have a question, should I create different api for admin login and end user login. I have different react and next frontend project for admin and end user. any help would be very much appreciated.

    @rammehar5531@rammehar55312 жыл бұрын
    • Not sure how this relates to this video, but IMHO, you should have one login for everyone and then have roles assigned to a user that gives them admin permissions, or not. Of course, I don't know your situation, so "it depends".

      @jherr@jherr2 жыл бұрын
  • unstable_batchedUpdates 🤯 I fixed a bug a while back by adding another conditional to a lengthy useEffect. I guarantee this was the root issue. Maybe I’ll dig up the old ticket and blow some minds with this tidbit 😏 And no, we’re still not on 18 yet 😢

    @dave6012@dave601211 ай бұрын
  • In general, would you recommend against using state with 'complex' objects? Anecdotally, I've always seen it used with scalar values and read that using complex objects can futz up things like re-renders.

    @thatboyneedstherapy@thatboyneedstherapy2 жыл бұрын
    • In this case I would recommend using a "complex" object. But yeah, it can mess up dependencies if you do something like [myStateObject] in the dependency, you should reference specific scalar values that you depend on like [myStateObject?.name].

      @jherr@jherr2 жыл бұрын
  • Hi! Can you tell me which extension suggest code like on 2:13? And if you like to make a video about usefull vscode extensions would be great.

    @jotapdiez@jotapdiez Жыл бұрын
    • That's GitHub Copilot.

      @jherr@jherr Жыл бұрын
    • @@jherr thanks

      @jotapdiez@jotapdiez Жыл бұрын
  • how do you realize the stuff

    @mohammadsaadati8359@mohammadsaadati83599 ай бұрын
  • What about using useReducer to update state instead of grouping all state in an object using useState? Any performance gains?

    @johan3040@johan30402 жыл бұрын
    • useState is just syntactic sugar on useReducer. So net effect should be the same. No perf gain, no perf loss.

      @jherr@jherr2 жыл бұрын
    • @@jherr setRoles(()=>{ Setotherproperty(()=>{return otherproperty}); return role}) ... does this work?...

      @avonflex5031@avonflex50312 жыл бұрын
    • @@avonflex5031 I haven’t tried that recently. Not sure if I would do that even if it worked. Non-contextual batching is coming so I’d go for the unstable thing first (if I couldn’t do compound state like I did at the end.) and then dump unstable at 18.

      @jherr@jherr2 жыл бұрын
  • Why isn't the roles array at 9:00 triggering infinite rerenders with the useEffect? Correct me if I'm wrong, but it seems like the roles array is being set to a new array reference within the useEffect every time it runs, which would trigger another rerender since it's changed and being tracked in the dependency array, and repeat.

    @Arunnn241@Arunnn2412 жыл бұрын
    • That's why I change it a useMemo that in turn create scalar from it. And anything that depends on that scalar will be trigger if the value of the string scalar changes, but that's disconnected from the array reference change.

      @jherr@jherr2 жыл бұрын
    • @@jherr I just found your channel a few days ago and I'm loving all of your content - it's been super helpful. I have a follow-up question here though - since info.roles is an array, why don't you run into an issue with your useMemo dependencies of recreating that object every rerender since arrays are referential equality? I hope my question makes sense. Thanks again! I'm really happy I found your channel!

      @Explosivehippo@Explosivehippo2 жыл бұрын
    • @@Explosivehippo I'll take a look but, I think it's ok because I'm converting array to a string. And then that string becomes the dependent.

      @jherr@jherr2 жыл бұрын
    • @@jherr Thanks for the quick reply, Jack! Can you point out where it's getting converted to a string? I see you're using JSON.stringify in your render, but that wouldn't mutatate the state value, correct? I'm probably just missing something - thanks again and keep it up!

      @Explosivehippo@Explosivehippo2 жыл бұрын
    • @@Explosivehippo Sorry man, maybe it's not. I've put up a bunch of videos around this topic and I think I got confused by which one this was. If I get some time I'll have a look later and see if I can be more helpful when it comes to understanding the example.

      @jherr@jherr2 жыл бұрын
  • Does react batch updates from useState and useReducer together? I mean will this cause one re-render?: dispatch({type: ''foo", payload: "some_value"}); setCount(10) where dispatch comes from react's own useDispatch & setCount comes from useState.

    @shivamjhaa@shivamjhaa Жыл бұрын
    • AFAIK state updates are batched. But it would be pretty easy to test.

      @jherr@jherr Жыл бұрын
  • Is it 100% necessary to use useMemo on roleList? I'm asking because every time info changes the component re-renders, therefor roleList can be written like this: const roleList = Object.keys....... and it will be always updated because of the re-rendering. Am I correct or I am missing something?

    @petarkolev6928@petarkolev6928 Жыл бұрын
    • It's not 100% necessary to use it. But if you have other stuff going on in that component that would also cause re-renders then you might be doing that roleList calculation unnecessarily and creating a new reference each time.

      @jherr@jherr Жыл бұрын
    • @@jherr Yep, makes perfect sense. Thanks a lot, Jack! I love your videos :}}}

      @petarkolev6928@petarkolev6928 Жыл бұрын
  • useReducer emit a large action

    @neaumusic@neaumusic Жыл бұрын
  • Hi Jack, I don't understand why your useMemo dependencies is array...? if you use array, you will get new array as long as you render your app

    @goldenmonkey9085@goldenmonkey9085 Жыл бұрын
    • you mean the base dependency array itself? That's not counted as an array ref for the purposes of the dependencies. reactjs.org/docs/hooks-reference.html#usememo

      @jherr@jherr Жыл бұрын
    • @@jherr I think Golden Monkey meant the info.roles array inside the dependencies array, same as objects, react will shallowly compare them between renderings and the useMemo hook will be re-run, then the useMemo hook is useless, am I correct?

      @tongvietanh365@tongvietanh365 Жыл бұрын
  • Can we expect backend tutorials in future?

    @rohithchittibommala2002@rohithchittibommala20022 жыл бұрын
    • In the next two weeks I'll be doing a backend tutorial.

      @jherr@jherr2 жыл бұрын
  • Vscode theme?

    @dhwajsharma@dhwajsharma2 жыл бұрын
    • Night Wolf [dark].

      @jherr@jherr2 жыл бұрын
  • The sound on the video is strangely louder on the left than the right speaker

    @ComfyCosi@ComfyCosi2 жыл бұрын
    • That's weird, I record in mono. Ah well.

      @jherr@jherr2 жыл бұрын
  • I don't know what react team is doing is anymore... it's like they have something in their mind, keep working towards it while breaking all the things one by one, making it less and less efficient...

    @dulanjala@dulanjala2 жыл бұрын
    • It's pretty hard when you have to maintain reverse compatibility and also push the feature set forward.

      @jherr@jherr2 жыл бұрын
    • @@jherr yeah! if you're doing something really good then it's fine, but what i feel is intentions are not aligned with dev community ( or at least me. ) just going whatever the direction that facebook wants to go... A great video idea would be to give some details about reacts future (if the details publicized by react team), why and what's happening sort of video.

      @dulanjala@dulanjala2 жыл бұрын
    • @@dulanjala I'm just a random guy, so I know about as much as you do (probably even less ;) ). But I can empathize with the React team in that they probably don't want to have a massive breaking change that will cause everyone to re-think sticking with React (a la Angular 1.5 -> 2). For example, I think the reason why we have dependency arrays is that setState in classes was just a value, not an observable. So useState needed to return a value, not an observable, so in order to do make that happen they needed to do dependency arrays and wow, lots of bugs happening from that. Anyway, I do think you are right that the React team's incentives are FB-first and not the dev community. Maybe that's why folks are so into NextJS, because the incentives there are clearly external dev focused and React is the view mechanism, but they layer a lot of value on top of it.

      @jherr@jherr2 жыл бұрын
  • I am really not a fan of react hooks. Iv been using for quite a while now. Everything is so hidden and convoluted.

    @SithLordBishop@SithLordBishop2 жыл бұрын
  • Your editor font is visually noisy

    @l3igmike@l3igmike2 жыл бұрын
  • What a beautiful font. It is immediately clear that the person did not write more than 3 functions in the document, but teaches others by retelling the documentation

    @graves3799@graves37992 жыл бұрын
    • yeah? and what have you contributed to society lately? I don't see you publishing helpful videos that explain concepts in meaningful terms that people can understand. instead you're on here adding nothing to the conversation, trolling, and being an ass. Does making comments like this help fill the void of your meaningless existence? Do you feel big and tough spewing negativity in youtube comments? Find something meaningful to do with your life or better yet seek some mental health counselling, this behavior indicates you you might have mommy issues or other deep seeded emotional problems.

      @thehaptiK@thehaptiK2 жыл бұрын
    • It is immediately clear that you are Nerf Herder.

      @designdeveloprepeat651@designdeveloprepeat6512 жыл бұрын
  • I have one question if i have fetched some data from an api and im setting loading state to false and in the next line of code i'm setting that fetched data inside my context. So will react batch the local component update and the context update or not? Something like this: setIsFetching(false); // local expensesCtx.setExpenses(expenses); // context api

    @mustaneerhaider515@mustaneerhaider515 Жыл бұрын
    • Depends on the React version, but I would either test it and see, or write the code as if both of those will update independently.

      @jherr@jherr Жыл бұрын
KZhead