This Context API Mistake Ruins Your Whole React App (All Components Re-Render)

  Рет қаралды 26,979

ByteGrad

ByteGrad

Күн бұрын

👉 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 Overview
0:38 Context API
1:08 Provider
1:32 Consume context
2:03 Huge mistake
3:17 Solution
4:03 Important: New provider
4:48 Crucial: Final
#webdevelopment #programming #coding

Пікірлер: 82
@ByteGrad
@ByteGrad 3 ай бұрын
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.
@ShantanuAryan67
@ShantanuAryan67 10 ай бұрын
3:15 the actual problem is - you defined state on App. whenever state changes the entire app rerenders, which includes the two example components. context is not the issue here.
@ByteGrad
@ByteGrad 10 ай бұрын
Yep, but beginners make this mistake in conjunction with the Context API
@ShantanuAryan67
@ShantanuAryan67 10 ай бұрын
the actual solution is - define state where it is needed - use composition to insert rendered trees directly in component
@ShantanuAryan67
@ShantanuAryan67 10 ай бұрын
fair enough 👍
@ukaszkrzywizna1756
@ukaszkrzywizna1756 8 ай бұрын
Thank you for this comment! As a React-dev beginner, I was very surprised as to why the context would cause the rerender of a whole app. Now everything's clear :) To author: Putting aside other videos (which are very helpful), this one causes more confusion than help.
@anonymoussloth6687
@anonymoussloth6687 8 ай бұрын
Can you explain how his solution avoids this? Why doesn't this happen again in the solution since the other components are child components as well
@jotaroisdarius1918
@jotaroisdarius1918 9 ай бұрын
i have a small suggestion, you should make more video likes this and group them into a playlist titled "common react mistakes" or something similar. Keep going dude!
@kashmirtechtv2948
@kashmirtechtv2948 5 ай бұрын
Yed
@anonymous_dev9472
@anonymous_dev9472 5 ай бұрын
Thanks for the clarity
@rm_4848
@rm_4848 9 ай бұрын
@2:45 Both components are re-rendering because of the state update in the parent, not specifically because of context usage. @3:47 You moved the state from the parent to the component level, so that’s why the other component doesn’t re-render.
@ByteGrad
@ByteGrad 9 ай бұрын
Yes, all true
@jackn
@jackn 9 ай бұрын
@@ByteGrad I still don't follow. In both cases, `CountContextProvider` and `App` are parent components with a `useState`. The only difference is in `CountContextProvider`, the `children` are passed as props and not as static JSX components. Why would a state change in `CountContextProvider` not cause the `children` props to re-render? I feel like there's some important information missing here
@ByteGrad
@ByteGrad 9 ай бұрын
Yeah, it’s tricky. What it comes down to is that the {children} pattern has special behavior that prevents that re-rendering. I might do a separate video on this
@The14Some1
@The14Some1 9 ай бұрын
@@ByteGrad Yes, please, make a followup, explaining this special behaviour. Recently i've watched Jack Herrington's video about context called "Making react context Fast" and he solves this problem in completely different way. I guess he is also not aware about this special behaviour of children.
@nark4837
@nark4837 9 ай бұрын
I would also love this!@@ByteGrad
@piush787
@piush787 4 ай бұрын
For those who still thinks why {children} did not render, the answer is in react docs: "When a component visually wraps other components, let it accept JSX as children. This way, when the wrapper component updates its own state, React knows that its children don’t need to re-render". @ByteGrad you are a savior but you must have mentioned this point too.
@Cypekeh
@Cypekeh 9 ай бұрын
Your videos are excellent. I got my first job as a react junior and I love how you explain thoroughly explaining your thought process
@Igor-vk8fl
@Igor-vk8fl 22 сағат бұрын
AMAZING! Simple and straight to the point
@andrewmcmaster7123
@andrewmcmaster7123 10 ай бұрын
That was a really nice demo! I had my code split like that but I didn't know that there was such a good reason for it to be done that way. Thanks for your well thought out and easy to understand video 🙂
@ByteGrad
@ByteGrad 10 ай бұрын
No problem 👍
@imfad3d
@imfad3d 3 ай бұрын
I've been using the right way for quite a while now but never bothered to know why. This video really puts thing in perspective. Good one.
@miraclenerdkidchiki6249
@miraclenerdkidchiki6249 9 ай бұрын
Thanks so much for the tips and tricks...you are doing an excellent job Great delivery and explanation as well as well though out code examples
@MyGeorge1964
@MyGeorge1964 10 ай бұрын
Keep 'em coming they're like little gems - thank you!
@ByteGrad
@ByteGrad 10 ай бұрын
Thanks, more to come
@giorgos6576
@giorgos6576 8 ай бұрын
Very clever trick. Any idea why the React DevTools (Tested on both Chrome and FF) thinks that the ExampleComponent2 re-renders even though nothing is console logged?
@bob_factory
@bob_factory 9 ай бұрын
I don't quite understand. I know the rerendering was caused by the state object on the main App function but even if you move the state over to another component shouldn't the children also rerender since the provider components state is being updated ?
@ukaszkrzywizna1756
@ukaszkrzywizna1756 8 ай бұрын
I think that this text from official docs applies here: "When a component visually wraps other components, let it accept JSX as children. This way, when the wrapper component updates its own state, React knows that its children don’t need to re-render."
@vineetsingh904
@vineetsingh904 Ай бұрын
i watched your 2-3 videos and all the mistake which you told I was making in my app but now i am fixing them. Your channel content is just like having a personal mentor.
@callegarip
@callegarip Ай бұрын
Thank you!. But what about if the ExampleComponent2component still needs to use the context but for a different state? Will clicking on the count button in ExampleComponent1 re-render ExampleComponent2 component?
@RADIOSCATRACHASUTAN
@RADIOSCATRACHASUTAN 28 күн бұрын
Man, I switched to Zustand when I saw this behaivior happening.. nice!
@stashladki2594
@stashladki2594 10 ай бұрын
Yeah, context API is definitely a tricky one, especially now with RSC's coming into play, I find that if properly done you almost never actually need to use contexts, less is more ;)
@wlockuz4467
@wlockuz4467 9 ай бұрын
using vanilla React with vanilla hooks is like shooting yourself, you just get to choose which weapon is it each time.
@YuretsUA
@YuretsUA 6 ай бұрын
Cool, thanks, I saw such code a lot in the applications but I thought it was made just for separation of logic, but now I see that it has other sence.
@Euquila
@Euquila 4 ай бұрын
I really love this video because it highlights some deep nuances in react. However, I feel like everyone is lost here, so **here goes**: The difference in rendering behavior stems from how components are incorporated into the component tree (direct inclusion vs. passed as children) and their data dependencies (like props, state, and context).
@funnyanimalvideosshow7780
@funnyanimalvideosshow7780 10 ай бұрын
Can you also make more landing page videos like you did earlier. the portfolio website was awesome. Next time can you touch on various niches, like product based etc. thanku for teaching all of these good things. keep going you have my support
@ziat1988
@ziat1988 9 ай бұрын
so should we get rid off context api and choose other state library like redux , zustand ...?
@oscardasilva971
@oscardasilva971 10 ай бұрын
I learn so much from you. Thank you so much
@ByteGrad
@ByteGrad 10 ай бұрын
Great to hear! 😊
@sck3570
@sck3570 9 ай бұрын
Wow I didnt know that, now I have a monumental task ahead of me
@nark4837
@nark4837 9 ай бұрын
This is great! I'd love for an explanation as to why simply moving the provider logic to a separate component stops both children from rerendering?
@nhathuynguyen716
@nhathuynguyen716 9 ай бұрын
yeah good point
@thecyberhobbit
@thecyberhobbit 9 ай бұрын
This is exactly what I was wondering when he started moving it and said to myself "why would that make any difference?"... to me it's those components are still be rendered INSIDE that raw context code.
@guanboyang
@guanboyang 9 ай бұрын
It's like you can't directly nested a server component inside a client component, but you can pass the server component as a prop such as children, right?
@brunocrosier
@brunocrosier 9 ай бұрын
nice! is there an eslint rule for this? 🤔
@Vishtar_Official
@Vishtar_Official 9 ай бұрын
Oh, i didn't thought about that. Thanks, man!
@rajeshkumarrout1192
@rajeshkumarrout1192 3 ай бұрын
wow thanks for such a deep explanation
@user-pw5do6tu7i
@user-pw5do6tu7i 9 ай бұрын
This video was clutch. Any suggestions for multiple contexts?
@Aashutosh_kumar
@Aashutosh_kumar 9 ай бұрын
You can use the same pattern of creating multiple contexts as separate component and wrapping them around the components that consume that context.
@Aashutosh_kumar
@Aashutosh_kumar 9 ай бұрын
One catch though, If you are working with normal React its fine, but If you are working with NextJs you should mark the component as client component by "use client" at the top of the file.
@aslamanver
@aslamanver 2 ай бұрын
use memo, or get the state out of
@rubadub_tv
@rubadub_tv 4 ай бұрын
Why does it require a custom hook to understand the state being used in children? Isn’t the context provider component already taking in children?
@richardpickman5574
@richardpickman5574 10 ай бұрын
So, ahhh, i trying to understand why this happends. I guess whole app component rerenders because app states changes, and then we using provider as wrapper component to let react just pass new arguments in reconciliation stage and avoid rerender, is it right or i am missing something?
@ByteGrad
@ByteGrad 10 ай бұрын
Yeah it’s tricky haha. In the mistake example, the whole app re-renders because the app state changes. In the solution only the state in the provider component changes and the children are not affected by that because of the {children} pattern
@CistiC0987
@CistiC0987 10 ай бұрын
Amazing stuff, also can you please explain why it is working? It looks the same to me, you just extracted provider to a component, no? Is there some magic because of thr children pattern?
@ByteGrad
@ByteGrad 10 ай бұрын
Yeah I should have mentioned it’s because of the state in the app component that everything re-renders. Then the solution is to use the {children} pattern which won’t affect children when state changes
@Eliac77
@Eliac77 10 ай бұрын
@@ByteGrad, I was looking for the explanation. Thanks for clarifying it here. Awesome job.
@yeasararefin007
@yeasararefin007 10 ай бұрын
Could you please make videos on : 1. How we can perfectly index a Next.js 13 Website on Google, How to get Our site on google search. 2. How we can integrate Google Ads in our Next/React website to earn from the site. I guess this topics are very important but we don't have enough content about this. Thanks.
@ByteGrad
@ByteGrad 10 ай бұрын
Thanks, good ideas
@hedgedog7706
@hedgedog7706 4 ай бұрын
Hello thank you very much for this video! I have a question - Why does every component render twice?
@daanw6270
@daanw6270 4 ай бұрын
Only in dev mode
@hedgedog7706
@hedgedog7706 4 ай бұрын
@@daanw6270 yeah but why
@user-rv7km5jy5c
@user-rv7km5jy5c 11 күн бұрын
would be nice if you go into "why" this happens
@wlockuz4467
@wlockuz4467 9 ай бұрын
This video is misleading. App re-renders because its own state changes not because of the context. What you did in CountContextProvider is no different than what you did in App, that is, you passed some children to a component. The real difference is that now your state is not bound to App, its bound to CountContextProvider. So as far as the App is concerned it has no state so it will never re-render, only the ExampleComponent1 which uses the context will re-render. As an experiment, if you you wrap your App in CountContextProvider and use useContext there, it will start re-rendering the whole thing again. 0:20 in the example you say the ExampleComponent2 needs access to state but you don't actually end up passing it, so what is the point of lifting it up? This makes it a very contrived example that doesn't really help the point you're trying to convey.
@ByteGrad
@ByteGrad 9 ай бұрын
Yep, all true, but this mistake is often made in conjunction with the Context API. It’s a contrived example, yes
@wlockuz4467
@wlockuz4467 9 ай бұрын
@@ByteGrad I think themes or login state are great examples for this
@The14Some1
@The14Some1 9 ай бұрын
@@wlockuz4467 Actually in case of themes rerendering of the entire app might be desired behaviour.
@dealloc
@dealloc 9 ай бұрын
@@The14Some1 Or y'know you could just apply a class on the document root HTML and have CSS handle the rest through CSS variables and media query. No re-renders needed, other than updating the state for whatever toggle you may have. Or otherwise, use a and FormData.
@anuragnair5672
@anuragnair5672 9 ай бұрын
nice!
@icodejs
@icodejs 9 ай бұрын
I tried this out and it works as you suggested in regards to console.logs, but when I select "Highlight updates when components render" within React DevTools, it still tells me that there was a re-render in both components. Any ideas? Maybe I'm doing something wrong 😊
@dealloc
@dealloc 9 ай бұрын
That is a bug in React DevTools because that feature hooks into the function calls. React calls all functions (including components) on every render. However, every render does not equal a function call. Nor does a render necessarily result in a DOM update. If you try to wrap your inner component's JSX in a single Fragment it should no longer highlight. Really you should consider using the profiler more than React DevTools for performance instrumentation that _actually_ has an affect. React DevTools is only really useful for searching through the VDOM tree for the most part.
@terjeber
@terjeber 6 күн бұрын
You should always use Typescript when developing React apps, none of this code compiles if you use TypeScript, which means there is something wrong with the code.
@rosan5657
@rosan5657 9 ай бұрын
can you make react-redux course please.
@ByteGrad
@ByteGrad 9 ай бұрын
My React & Next.js course will have Redux too. Make sure you’re subscribed to the email list :)
@rosan5657
@rosan5657 9 ай бұрын
@@ByteGrad your videos are So informative then regular courses Thank You. btw m from Nepal
@DjLeonSKennedy
@DjLeonSKennedy 9 ай бұрын
It's cool but for me who nows why it's working like this, video should describe it also I think
@prasadbroo
@prasadbroo 8 ай бұрын
You told us which pattern to use but haven't told us reason behind it Sorry for my bad English😊
React Hook Form (+ Zod) - Complete Tutorial
31:21
ByteGrad
Рет қаралды 78 М.
WHY DOES SHE HAVE A REWARD? #youtubecreatorawards
00:41
Levsob
Рет қаралды 30 МЛН
Follow @karina-kola please 🙏🥺
00:21
Andrey Grechka
Рет қаралды 26 МЛН
ELE QUEBROU A TAÇA DE FUTEBOL
00:45
Matheus Kriwat
Рет қаралды 14 МЛН
ПЕЙ МОЛОКО КАК ФОКУСНИК
00:37
Masomka
Рет қаралды 10 МЛН
The important things to know about React state and renders
18:33
Web Dev Cody
Рет қаралды 25 М.
TypeScript Generics are EASY once you know this
22:21
ByteGrad
Рет қаралды 120 М.
Why Signals Are Better Than React Hooks
16:30
Web Dev Simplified
Рет қаралды 448 М.
Mastering React Context: Do you NEED a state manager?
37:26
Jack Herrington
Рет қаралды 96 М.
Making React Context FAST!
33:34
Jack Herrington
Рет қаралды 84 М.
Why I don't use React-Query and tRPC in Next.js
18:58
ByteGrad
Рет қаралды 68 М.
Stop using div in React (+ Fragment, Semantic Tags)
15:48
ByteGrad
Рет қаралды 113 М.
Why use Type and not Interface in TypeScript
14:12
ByteGrad
Рет қаралды 188 М.
Learn React Hooks: useContext - Simply Explained!
15:46
Cosden Solutions
Рет қаралды 119 М.
The Story of Next.js
12:13
uidotdev
Рет қаралды 532 М.
WHY DOES SHE HAVE A REWARD? #youtubecreatorawards
00:41
Levsob
Рет қаралды 30 МЛН