The correct way to optimise React

  Рет қаралды 31,385

Cosden Solutions

Cosden Solutions

10 ай бұрын

Join The Discord! → discord.cosdensolutions.io
VSCode Theme | Font → Material Theme Darker | Menlo
It's finally time we talk about the correct way to optimise React. I see a lot of developers using React hooks like useMemo and useCallback wrong, and actually trying to over-engineer performance. This can even lead to, ironically, worse performance than you had to begin with! I show some examples here to hopefully clear this up once and for all, so that we can all go back to building performant React applications.

Пікірлер: 67
@rmnkot
@rmnkot 10 ай бұрын
Let's don't forget about one important thing. React will re-render child component anyway regardless of wrapping variables or functions in hooks on parent render unless you wrap it in memo HOC. This concept is skipping in most of the videos like this which forms wrong mindset around this problem.
@cosdensolutions
@cosdensolutions 10 ай бұрын
Yes, made a comment in the vid I forgot to add it! But definitely!!
@miraclenerdkidchiki6249
@miraclenerdkidchiki6249 10 ай бұрын
So true bro....i always try to keep state local so as to prevent the parent from unnecessarily re-rendering and consequently the children. Basically, if its not needed elsewher, keep it local.
@federico9505
@federico9505 10 ай бұрын
​@@miraclenerdkidchiki6249how do you keep it local?
@ZelarKyton
@ZelarKyton 10 ай бұрын
useMemo for expensive computation memo for preventing diffing a lot of markup unnecessarily when parent component re-renders, especially in loops useCallback for avoiding breaking children's memos when you need to pass callbacks to children with good amount of markup The saddest situation is probably when you need to close on some props and state in parent component's "action" callback, and pass that to the mapped children. One of the ways to fix it is this hacky hook: export const useEvent = Any>(cb: T): T => { const ref = useRef({ cb, wrapper: (...args: Any[]) => ref.current.cb(...args), }); useLayoutEffect(() => { ref.current.cb = cb; }); return ref.current.wrapper as T; }; This will have a stable reference and always fresh underlying callback. The only downside is that underlying callback and values it closed on will be one render behind latest if called from `useLayoutEffect` in child components, since child components run their effects first. Something like SolidJS would do granular updates for you, no matter where you put the state, but in react you need to think where to put state and how to split components to keep state-inflicted re-render cheap.
@MrEnsiferum77
@MrEnsiferum77 9 ай бұрын
Not if they are send as props, tree it's split then...
@KoOcie92
@KoOcie92 10 ай бұрын
@vishwasrv Correct sir, primitives such as strings, numbers or booleans are compared to each other by their value, where arrays, functions or objects are compared by their reference in memory. In other words on each re-render non-primitives are having a new reference, therefore using them in dependency arrays is just counter-productive. This is actually the most common mistake made even by the senior devs. That being said it is worth to mention that states in react if not changed directly, preserves their reference... which just introduce more confusions...
@soundsoflife808
@soundsoflife808 7 ай бұрын
Extremely useful content as always!
@deepakkashyap6538
@deepakkashyap6538 10 ай бұрын
Awesome explanation 🔥
@pedR
@pedR 7 ай бұрын
Once again great video!!! How can we evaluate the cost performance of each aproach? It would be interesting to do a video with metrics?
@pororit
@pororit 2 ай бұрын
its so good point for optimisation! thanks!
@teflonhav
@teflonhav 22 күн бұрын
top tier channel
@vishwasrv
@vishwasrv 10 ай бұрын
I have a doubt sir , passing objects as dependancy array in usememo or callback will always create new instances isnt it? In that case its better to use primitive values within the objects as dependencies, please correct me if I'm wrong?
@cosdensolutions
@cosdensolutions 10 ай бұрын
in theory yes, but here we're passing state, which doesn't get re-created. Even if state is an object
@vishwasrv
@vishwasrv 10 ай бұрын
@@cosdensolutions oh okay thanks sir will keep this in mind , so if it's an object from a parent passed down as a prop , then it would make sense to pass the primitive values I suppose
@asadmalik5075
@asadmalik5075 10 ай бұрын
Useful Man
@CoericK
@CoericK 2 ай бұрын
What about wrapping the UserStats component with a React.memo(UserStats) ? What that be low performant as well?
@coder5877
@coder5877 10 ай бұрын
It’s seem logical to think that useMemo and useCallback is not cost less and perhaps we should be using it more sparingly. But another thought that came to mine was the presentation given on the React compiler that meta is working where useMemo and useCallback is applied by the framework itself. In that case I’m wondering on what basis it will apply the optimization or if they feel like the cost is negligible and apply it across the board.
@miraclenerdkidchiki6249
@miraclenerdkidchiki6249 10 ай бұрын
I also heard of that new upcoming algorithm where React can automatically optimize certain components...but i believe its still in the works and has not been released yet
@cosdensolutions
@cosdensolutions 10 ай бұрын
can you link to that presentation? I've heard about this but never actually seen something concrete
@HarshShah465
@HarshShah465 5 ай бұрын
Can you please create video on how to measure how many time rerender happens on clicking or any event?
@supersaiyan2
@supersaiyan2 10 ай бұрын
I am new to react, but if user is a state, wont user stats automatically get updated when user is changed? Whats the point of a useMemo?
@cosdensolutions
@cosdensolutions 10 ай бұрын
yes it would, the point of useMemo here was to stop userStats from getting re-created if anything else than user changes. Ideally you only want it to change from user, not from anything else that might come up in the component. Usememo fixes that
@garikmelqonyan6011
@garikmelqonyan6011 10 ай бұрын
Good tutorial
@isaacjon
@isaacjon 10 ай бұрын
I have an idea. imagine we have a page where at the top we have 3different filters and based on that we display an infinite number movies and also we have a search bar. You u need to make sure that everything is written like a senior developer to make this page the most optimized
@cosdensolutions
@cosdensolutions 10 ай бұрын
Absolutely
@pavelisel4127
@pavelisel4127 10 ай бұрын
I'm still waiting for someone to give an example of an expensive computation, everyone says is for that but no one has ever given an example 😥
@cosdensolutions
@cosdensolutions 10 ай бұрын
map over 10k items in an array
@balduin_b4334
@balduin_b4334 10 ай бұрын
whouldnt be the best optimization to use 2 variables instead of one obj?
@cosdensolutions
@cosdensolutions 10 ай бұрын
that would make no difference in terms of performance here. It would only be better or worse depending on the project and how it's structured!
@Glinkis
@Glinkis 10 ай бұрын
Accessing properties of an object will always be slower then accessing variables. Objects are also worse for the garbage collector since they have to be allocated and in memory, in edition to the values that they store. But keep in mind these things don't matter unless you have a lot of them, or is accessing them in a very tight loop.
@balduin_b4334
@balduin_b4334 10 ай бұрын
@@Glinkis^
@PwrXenon
@PwrXenon 10 ай бұрын
Greatest way to optimize it is to remove it entirely from your project
@victorduarte4059
@victorduarte4059 10 ай бұрын
How can the performance be tested?
@cosdensolutions
@cosdensolutions 10 ай бұрын
you can measure it manually, or use the react dev tools profiler
@noherczeg
@noherczeg 10 ай бұрын
3:46, yes, but we are filling the garbage collector with dead weight. which could lead to longer gc periods.
@cosdensolutions
@cosdensolutions 10 ай бұрын
I wouldn't worry about that
@user-ut4hj7kc1t
@user-ut4hj7kc1t 4 ай бұрын
What make expensive calculations being expensive? Where it starts? Where is the border?
@user-fr6gw8xr4b
@user-fr6gw8xr4b 10 ай бұрын
Isn't comparing to reference super fast. It is comparing two pointers. On another hand if the is object big and component rerenders a lot, the GC will not be very happy
@cosdensolutions
@cosdensolutions 10 ай бұрын
there is a cost, not 100% sure how deep it is, but it's always better to do things by necessity to avoid any overhead
@shaz101
@shaz101 3 ай бұрын
1000th like ❤
@nonnnth
@nonnnth 10 ай бұрын
This looks unnecessarily complicated. Can I just useSvelte or other frameworks instead.
@cosdensolutions
@cosdensolutions 10 ай бұрын
sure
@un_defined
@un_defined 6 ай бұрын
solidjs
@wlockuz4467
@wlockuz4467 10 ай бұрын
Being highly nitpicky here, but this is still not optimized because its still creating and destroying an object on each render. If you really care about small performance gains then you should write a utility function outside of the component for both cases.
@cosdensolutions
@cosdensolutions 10 ай бұрын
I think worrying about that kind of thing isn't worth it tbh. The idea of this video was how to use useMemo and useCallback properly, because those are bigger issues than the creation of objects and what not
@erezmizrahi1631
@erezmizrahi1631 10 ай бұрын
its meaningless If you use an object in the dependency array of useMemo.. the object will always have a new reference when the component re renders
@cosdensolutions
@cosdensolutions 10 ай бұрын
not if it's state
@mcdaddy1334
@mcdaddy1334 10 ай бұрын
0:27 ONE PIECE
@archmad
@archmad 10 ай бұрын
make an object as dependency is a red flag. That actually is the biggest sin
@cosdensolutions
@cosdensolutions 10 ай бұрын
not really, you usually pass objects as props for example if you have a user, or a post, or a comment, etc. It's a very common pattern
@archmad
@archmad 10 ай бұрын
@@cosdensolutions you need to check how it is doing the comparison. it is always better to use primitive types than arrays/objects
@YasinAkimura
@YasinAkimura 9 ай бұрын
For a state object it is fine to pass it as dependency as it's easier comparing by reference once instead of comparing each member. If any value changed inside the user state object the reference will change anyways by definition of how react works.
@archmad
@archmad 9 ай бұрын
​@@YasinAkimura that maybe true, but a good practice, please dont
@MrREALball
@MrREALball 10 ай бұрын
The other use of useMemo, besides expensive operations, is if you need to have a more stable reference to an object. Also, you forgot that theres an additional cost for creating a callback function and a dependency array for useMemo.
@ranadenish
@ranadenish 10 ай бұрын
Sorry, but you can't just write your mistake in "Video Comment" directly. Someone might not read it correctly and will get bad concept. --- You might want to re-edit/re-shoot the video, but don't compromise quality.
@cosdensolutions
@cosdensolutions 10 ай бұрын
that's a fair point. I didn't have the opportunity to re-film this as I left for vacation the day after. For what it's worth, there is a visual comment inside the video saying my mistake, so some people should have seen it. I'll be more careful moving forward. Regardless, the rest of the video still applies and is valid, even with this mistake
@isaacjon
@isaacjon 10 ай бұрын
Bro make more practical stuff, this is too basic.❤❤
@cosdensolutions
@cosdensolutions 10 ай бұрын
Well not basic enough, I had to make the vid because a lot of people understood it wrong!
@iCodeArtisan
@iCodeArtisan 2 ай бұрын
Quite often it's these "basic" stuff that a lot of us miss.
Learn React Hooks: useCallback - Simply Explained!
17:15
Cosden Solutions
Рет қаралды 80 М.
8 React Js performance optimization techniques YOU HAVE TO KNOW!
11:23
Beautiful gymnastics 😍☺️
00:15
Lexa_Merin
Рет қаралды 15 МЛН
УГАДАЙ ГДЕ ПРАВИЛЬНЫЙ ЦВЕТ?😱
00:14
МЯТНАЯ ФАНТА
Рет қаралды 3,9 МЛН
Cat Corn?! 🙀 #cat #cute #catlover
00:54
Stocat
Рет қаралды 16 МЛН
This is way too complicated! - Code Review
19:31
Cosden Solutions
Рет қаралды 21 М.
Learn React Hooks: useRef - Simply Explained!
12:42
Cosden Solutions
Рет қаралды 87 М.
You Probably Shouldn't Use React.memo()
10:17
Theo - t3․gg
Рет қаралды 53 М.
You might not need useEffect() ...
21:45
Academind
Рет қаралды 154 М.
Why Signals Are Better Than React Hooks
16:30
Web Dev Simplified
Рет қаралды 464 М.
Every React Concept Explained in 12 Minutes
11:53
Code Bootcamp
Рет қаралды 493 М.
Learn React Hooks: useMemo - Simply Explained!
13:41
Cosden Solutions
Рет қаралды 86 М.
Stop Doing this as a React Developer
12:27
CoderOne
Рет қаралды 161 М.
Beautiful gymnastics 😍☺️
00:15
Lexa_Merin
Рет қаралды 15 МЛН