Rather than creating a custom hook just for storing related state, useReducer can be more ergonomic as it can also provide you with a single dispatch function that can update that state using actions. As for the second point about nesting; this also comes with a gotcha in that the parent component will update all its children when it updates state that may just be used for a few or a single child. It's useful if child components are reusable, but unnecessary otherwise. It's fine to co-locate state and event handlers in child components and is often easier to reason about; If you truly run into performance issues due to unnecessary re-renders, you can wrap child components in React.memo.
Thanks again for the tutorials Jeff your style of teaching is very straight forward and to the point. I am curious if anyone has seen a similar extension for JetBrains (glean)
That's why more opinionated frameworks like Vue exist, so you don't have to learn every way you can do stuff. I myself would honestly stick to Svelte for personal projects, it's one of few frameworks that don't actively piss you off on each step. (And yes, React is a lib - as long as you don't slap JSX on top of it)
@@amirhoseinhesami9336 react came first and that was huge advantage.. i would go with vueJS or svelte or even angular for complex Enterprise apps. The non opinionated react is not really my thing
@@lahcencodery vue and svelte in the enterprise world is not a real thing and also the funniest joke ever however the "angular" used to dominate the enterprise world however it is not relevant today because react is dominating the enterprise as well
I just got accepted as a frontend dev on a startup company. A year ago, CEO hired some devs to create mobile app and web app using react native. Devs finished the contract and left. And this is where i get in. Imagine me, a react newbie, who have to fiddle with a messilly coded and stinky class based component react app. The worst part is, there's almost zero class based component tutorials on youtube. At least the pay is nice
@@user-yy3ki9rl6i I'd avise you to rely on the React docs, fortunately they have an excellent documentation (which is actually rare), and with plenty of class-based examples. And try sell your boss a progressive refactoring of your code.
i remember when my team first work on React before it got hooks but 3 months later, hooks got introduced and people didn't want to jump ship. tried convincing others to move all to hooks, but too late. we end up half of the code in hooks
@@user-yy3ki9rl6i the majority of react developers stop using classes and try to avoid it. because functions give almost the same result and with more readable and clean code. classes still has some render cycle methods that are not exist in functions but you will not need them in 90% of the cases.
@@user-yy3ki9rl6i I set aside an hour every workday to refactor one or two class components into hooks-based function components. A week of that taught me more about the codebase than the previous two months, and after two weeks my boss took me aside and asked me to refactor everything. Refactoring to hooks is such a win in performance and complexity that you should try to make it happen however you can, everyone around you will notice the improvements quickly
Great video! When you work with react every day for a few years, you slowly realize exactly the things you showed here. It would've been nice to see this 2 years ago :)
I think that when you have prop drilling issues, before reaching for context or redux, it's usually best to consider if you are using the `children` prop effectively. A lot of the time if you aren't using the drilled prop in the intermediate components, they can render `{children}` and that prop can be passed directly from the origin parent to the component that needs it.
@@Bobobratwurscht You have a parent component and a child component. The parent component accepts a bunch of props which are just used to pass (or drill) it to the child component. What you can do instead is to just accept a children prop in the parent component and render it. When you now render the parent component, you pass the child component as the children prop of the parent.
Very important thing with context - any item that consumes that context (i.e., the `const count = useContext(CountContext);` in the example) will ALWAYS rerender when the context value changes, regardless of if that component actually uses that value or not. A very common pitfall is to use Context as a sort of 'big store', where you've got a ton of values in the context that are consumed by components that only need one or two of said values. This means that every time the context component updates, EVERY SINGLE CHILD COMPONENT THAT RELIES ON THAT CONTEXT WILL ALSO RERENDER. It's a huge, huge performance issue in very large apps. Keep context to items that will change extremely rarely - themes, authentication states, etc - and never use them for data that changes somewhat frequently unless you're making a very tiny app that won't see the exponential performance loss of this. If you need something passed down but don't want to go through the whole heavy mess of Redux / MobX / etc, minimalist state management libraries like Recoil, Zustand, and Jotai are very easy, approachable, and lightweight ways to do this the 'right' way.
@@adeleke5140 yes that’s how react does it meanwhile other frameworks only re render what needs to be re rendered when you call the info somewhere and not every spot that your store somehow reaches its a stupid expensive way to make sure your UI is updated
Some of these are anti-patterns as well. Spreading props is an anti-pattern because it is not declarative and it can cause unneeded exporting of types between components. Additionally, your curried function should be nested within a useCallback() to prevent extra re-renders. If you want to teach against anti-patterns, it would be better if you taught your audience eslint recommended settings for common plugins.
I agree with the second half but not so much as the first. Spreading is a fine pattern if you as the developer are aware of what you are doing. Not to mention typescript ensures you use it properly
@@_guru ESLint has a bunch of default rules, but if you really wanna give it a go, try the Airbnb rules. Those are opinionated, and I enjoy them very much.
when fetching data, the AbortController (native API) can be used, or a library that abstracts this away or avoids this issue can be used, like react-query
**looks at the video title** anti-patterns of react.... 😑 Use vue or svelte 🤷🏻 Your videos are addictively informational... Somebody save me from this guy 😂
edit: apparently currying is still the correct term, i've just never ever seen it used for general function generation. regarding 9: in the example that _you show_ it's a curried function, but what _you describe_ is just a factory function. curried functions basically let you specify the multiple arguments of a function A in multiple steps where each step or function call returns you a function where that value is "stored" in the closure and you can specify the next argument with the next call on the returned function.
@@creatorsremose they're not. currying means the final function arguments get composed in this staged fashion. every curried function is a function factory, but function factories don't have to receive or provide any arguments up or down the chain. when working with react, you probably never need currying.
@@BuyHighSellLo it's a functional programming pattern for when you have a target function with more than one argument. if you look up currying you should find good examples.
He is correctly describing a curried function. Also, factory functions return objects, not functions (unless we're being strict with how we define a function in Javascript).
Hey, I've actually thought of using curried functions, but my initial thoughts tell me that it is going to going to consume more memory as for each call, a new big function will be made again to be called. In contrast, the one without function currying I suppose would call the same function, not create a new one, but with different params, hence better perf and memory. I have yet to test if this is true or not. Is that how it works in JS? I'd like to know the results for this.
Doesn't matter. With curried function on 3 calls you create and return 3 functions. If you use 3 arrow functions, you created them as well, but manually, not programmatically.
I don't think that's the case. See, what you're thinking is that the onChange function runs the currying on every call, but what it does is that each call runs the returned function. The curry function only runs on re-render.
@@isqueirosbic Idk if you were responding to me or Nathan, but let me make it clear: In both cases on each render you create three functions that live in memory. In the first example you create them manually writing three arrow functions. In the second example you create those three functions by running the "creator"/"factory" function. In the second example you have "more calls" but that doesn't matter. The memory footprint is close to being exactly the same.
In either case, it creates 3 new functions on every render. If you *really* want to try to avoid this, you can create a useCallback function but this is most likely overkill over-optimisation. const handleClick = useCallback((param) => (event) => clickHandler(event, param, state), [state]) Button text
@@niklasstahl98 Not really. Most JS developers with a little bit of experience will be familiar with the fundamental types. It's only jarring for the first couple of days using them in a strict manner but after that it becomes natural.
TypeScript, deservedly, gets a lot of praise, but it's really under-discussed how much you have to change the way you code in order to use it properly. I think it's lighthandedness is pretty overstated
@@teacul I personally don't try to fight it too much, it's an addition here to simplify our lives but if it ends up becoming cumbersome that's not a great deal anymore
WHAT, I always create children with a function IN the component, without props. Oh my god, I feel so stupid now. Time to refactor and test the performance I guess
If you curry a javascript function in es6, you dont' need the braces and return statement, you can double up on the arrow syntax: const handleIt = v => e => console.log(e, v) equivalent function to the one shown at 7:31
For subscribing to state, it's ok. But you're right that if you need to update state, you'd need a way to provide those dispatch functions. An alternative is to use useReducer instead, which gives you a single dispatch function that you can use to update state through actions.
Prop drilling is made a bigger issue than it really is. If you're drilling more than 3-4 levels deep then you have an architectural issue, not a state issue. Redux causes more headaches than prop drill itself.
Another useful feature "functional state update" if the new state depends on the previous state, you can pass a callback to setState like `setState(previousCount => previousCount + 1)` instead of `setState(count + 1)` Using functional state update will help in the memoization of the event handler using `useCallback` as the dependencies can be an empty array and it will also help in avoiding stale state closures
Yeap..it is a known issue. Everytime you need the current state value always use the callback. You can even end up in weird bugs if you the state value gets stale (like in an interval)
React's flexibility comes with great responsibility. I once worked on a React project where everything is memoized. We thought it would improve performance, but lately I realized it was a premature optimization
Definitely a problem I see often. Using memo/useMemo/useCallback is a tradeoff between spending processing time and memory. JavaScript engines are really fast nowadays, and React isn't slow either. For most UI you won't notice any performance issues unless you do something really complicated; at which point you have a few options; If your component does something that results changes the DOM or needs to do offload rendering where it doesn't matter whether React can keep track of it, you can use imperative APIs; e.g. for animations. You can use refs to grab the context of underlying DOM nodes of React elements you want to access. In most cases, splitting out components into logical parts that can do their own work, such as subscribing to specific state or doing computationally expensive things that aren't easy to optimize otherwise, you can memoize it, optionally with a comparison function. The less props you pass those expensive components the easier it becomes to manage at the cost of less reusability-again a compromise you'll have to make.
And probably introduces other ones, having to rewrite your entire codebase for one ;). All have their pros and cons, much more useful to figure out where to use one or the other.
0:12 There is no way into that maze with the entrances in front of that guy lol. One leads straight back out and the other is a dead end. Unless the one that leads straight back out is the solution.
for the context API i like to use this pattern where i have a single file that - creates the context with the default value undefined, but does not export it - creates and exports a provider component - creates and exports a custom hook that uses useContext and throws if the context value is undefined this way you always only import one thing (useMyContext hook) and you'll also always immediately know if you're using a component and there's no provider in it's parent hierarchy.
@@shawnc7381 I can't post a link here, but google "kent c dodds how to use react context effectively" there's a post on his blog that covers this pattern.
Just a little bit more relaxed narration and it would be perfect. And a breather between each section. If you are only listening, it's hard to know when you start talking about a different thing.
While I do agree with basic tricks, I don't agree with some of the points you made; 1 - While big components are harder to read, extracting a component just for the sake of it is also a bad experience, which I consider an anti-pattern. Like Nav that you show there, if you are not going to reuse that component ever, there is no point of extracting it. Long trees of HTML is nature of the web, you can't escape from it, what you essentially do there is hiding it. While this might come in handy in some situations, I don't think this is a go for everything, usually not worth the complexity if it doesn't have an internal state. 5 - I strongly disagree with this. I don't know if you ever take over on a project someone else made with file per function/component. I did recently, 2 times a row. It takes so much time to get into project, figure out what's what. Usually people doing that cross reference everything from eachother, which makes you hop from file to file as everything references everything. This approach is popularized by companies like Facebook, for the case of React, to take advantage of their monorepos and cross-use functions/components between files. If you are not at the scale of Facebook, I don't think that's necessary. I do categorize my components as unique and generic. If it is something like a button, or input, table etc., which is used multiple times in different place, *with different props*, that's a generic component for me. Sure, I do create their own files for them. They don't cross reference except in several cases. So it isn't like matryoshka, you don't find another component hidden inside another, which was hid inside another and so on. If a component is unique, like a section of page, having a purpose, specific state and so on, I do put them into another folder, each into their own files. One important thing here is, if those components require child components to render, I do define them on the same file (though I don't export them, they are internal). This helps much to reduce files I need to name and traverse. For functions, I tend to put lots of related things into big chunks of files. If it becomes too big or there are specific kind of functions piling up, I do seperate them into another namespace. But doing function per file is quite overkill for me. So I'd say it is a balance between piling everything into same file vs putting everything into their own files. I was doing the latter 2 years ago, which become a maintainance hell for me quickly, so reduced it and happy with it, so I consider it an anti-pattern. 7 - Redux isn't for prop-drilling, as you say it is overkill, but I wanted to emphasize it. Other than those, nice video. I do remember a video of you comparing some React code, which I commented about anti-patterns in that video; happy to see that you are using React extensively and creating React courses!
2 роки тому+5
React itself suggests to use `containment` or `composition` first before even considering the react context API: reactjs.org/docs/composition-vs-inheritance.html
Yep. For some reason, I've found that new devs latch on to the "prop drilling = bad" concept pretty quick, and they reach for the context API first. An explosion of random grab bag contexts ensues...
@@godoftheLTD Indeed. Context comes with its own tradeoffs that are easy to miss; especially if you use it for anything else but dependency injection. Contexts can be useful for isolated component trees that needs shared values deeply. But for global state management, it's often better to use state management libraries that are optimized to avoid unnecessary re-renders. In most cases passing props down 2-3 layers is fine.
Why did you take a break if I may ask?, Was it due to a burnout or something like that?, I'm just curious so you don't have to answer if you don't feel like doing so :).
@@daumienebi I started a marketing and business development company. So for the majority of my time doing other things. I still built websites and coded it was just in WordPress more than anything so mostly code snippets and changing things in a theme. Recently, my company has grown to the point where I can spend some time doing new things and I picked up design and software development a lot more!
In number 9 while technically correct there is a pretty decent size caveat. React 16 and 17 will batch setStates as long as it not in an async function. If you are in an async function you can use unstable_batchedUpdates to batch setStates. The latter being pretty hacky in my mind, but can save you from a large refactor
Am I the only developer who hates react? I know it has it's place, but every time I see react code I just cry at the performance loss and the junior devs do whatever in react because the state is managed for you!
Man you are a genius. Your channel and then 10 places are empty and then everyone else, it's amazing how original you are with content and just keep going! Big greetings from Serbia! :)
For the currying comment, rather than having a function outside of the component, use a useCallback or with every render it's producing a new function which then means when you're passing that as a prop it's seen as a prop change and causes a re-render for those components
Chapter 1 1 In the beginning God created the heaven and the earth. 2 And the earth was without form, and void; and darkness was upon the face of the deep. And the Spirit of God moved upon the face of the waters. 3 And God said, Let there be light: and there was light. 4 And God saw the light, that it was good: and God divided the light from the darkness. 5 And God called the light Day, and the darkness he called Night. And the evening and the morning were the first day. 6 And God said, Let there be a firmament in the midst of the waters, and let it divide the waters from the waters. 7 And God made the firmament, and divided the waters which were under the firmament from the waters which were above the firmament: and it was so. 8 And God called the firmament Heaven. And the evening and the morning were the second day. 9 And God said, Let the waters under the heaven be gathered together unto one place, and let the dry land appear: and it was so. 10 And God called the dry land Earth; and the gathering together of the waters called he Seas: and God saw that it was good. 11 And God said, Let the earth bring forth grass, the herb yielding seed, and the fruit tree yielding fruit after his kind, whose seed is in itself, upon the earth: and it was so. 12 And the earth brought forth grass, and herb yielding seed after his kind, and the tree yielding fruit, whose seed was in itself, after his kind: and God saw that it was good. 13 And the evening and the morning were the third day. 14 And God said, Let there be lights in the firmament of the heaven to divide the day from the night; and let them be for signs, and for seasons, and for days, and years: 15 And let them be for lights in the firmament of the heaven to give light upon the earth: and it was so. 16 And God made two great lights; the greater light to rule the day, and the lesser light to rule the night: he made the stars also. 17 And God set them in the firmament of the heaven to give light upon the earth, 18 And to rule over the day and over the night, and to divide the light from the darkness: and God saw that it was good. 19 And the evening and the morning were the fourth day. 20 And God said, Let the waters bring forth abundantly the moving creature that hath life, and fowl that may fly above the earth in the open firmament of heaven. 21 And God created great whales, and every living creature that moveth, which the waters brought forth abundantly, after their kind, and every winged fowl after his kind: and God saw that it was good. 22 And God blessed them, saying, Be fruitful, and multiply, and fill the waters in the seas, and let fowl multiply in the earth. 23 And the evening and the morning were the fifth day. 24 And God said, Let the earth bring forth the living creature after his kind, cattle, and creeping thing, and beast of the earth after his kind: and it was so. 25 And God made the beast of the earth after his kind, and cattle after their kind, and every thing that creepeth upon the earth after his kind: and God saw that it was good. 26 And God said, Let us make man in our image, after our likeness: and let them have dominion over the fish of the sea, and over the fowl of the air, and over the cattle, and over all the earth, and over every creeping thing that creepeth upon the earth. 27 So God created man in his own image, in the image of God created he him; male and female created he them. 28 And God blessed them, and God said unto them, Be fruitful, and multiply, and replenish the earth, and subdue it: and have dominion over the fish of the sea, and over the fowl of the air, and over every living thing that moveth upon the earth. 29 And God said, Behold, I have given you every herb bearing seed, which is upon the face of all the earth, and every tree, in the which is the fruit of a tree yielding seed; to you it shall be for meat. 30 And to every beast of the earth, and to every fowl of the air, and to every thing that creepeth upon the earth, wherein there is life, I have given every green herb for meat: and it was so. 31 And God saw every thing that he had made, and, behold, it was very good. And the evening and the morning were the sixth day.
Great video! It’s crazy to me though how many of these patterns are encouraged out of the box with something like SvelteKit. First principles approach with a clean slate has done the Svelte team wonders.
Awesome, educational video! Really appreciate the effort (and also the humor) that went into this. Also, this is the first tutorial video I watch on default speed and not 1.5x 😅
As these fine gentlemen suggested, you define a ```[state, setState] = useState('foo');``` inside your parent component. Then you pass the setState function to the children like so ``` ```. Within the child, you ```function Child({ state, setState }) { ... }``` and you can now use the setState defined in the parent component within the child component, to update the state in the parent itself. BTW, *use names with proper semantic meaning*, because "state" means nothing. Think of yourself 15 days later trying to remember what that variable was supposed to store.
@@3_smh_3 I’ve done this before and it can result in loss of referential stability. This leads to unpredictable behavior and excessive renders. The child will Render multiple times whenever the parent does as that function recalculating its value counts as a “prop change” If you want to encapsulate it, you can avoid this by wrapping the function in a useCallback hook and including the new value inside the dependency array.
Unfortunately, in my humble opinion, THIS IS THAT. React is the worst web framework compared to the others. Common patterns and functionalities that should be transparent, automatic, and a developer should not worry about them when coding a solution because they must be present in any web app, with React you need to care about all the time and manually repeat in any component code. That results in useless work (not focused on the solution itself) and tons of workarounds to deal with React issues.
Unfortunately I'm learning React because there are no Vue jobs where I live... I don't like the fact that I have to use a lot of libraries with it to make stuff minimally manageable without being a pain in the ass (form handling, two-way data binding, etc...).
i know i'm late to the party, but this is a lot to do a few simple things. I am coming from vue and needed to see habits for react development. no offence though, I think both get the job done, but react is more common in this region. That refactor markup -> component thing is really good.
I love your videos, but please, do not include images that may affect people sensible to gore. People who undergo brain surgery often become very sensible to such images/videos. That drill was unnecessary. Love your content. Cheers
Please Please Please remove 9th Curry section! this is a huge performance anti-pattern!!! The function returning new function always, and component which is using this returned new function will re-render together with parent component all the time! You have to use useCallback on functions before passing it to the prop, and you can't use useCallback on curried inner function!
7:31, I couldn't think of that. I was at least familiar with some coding tips you have provided until 7:31 as i am watching, but i knew that i can return a function.
Re: the currying example, I'm not a big fan of coding "to impress my friends and family" haha. I'd rather it be as simple and unimpressive as possible.
5. That only works if you style your components with plain css, however most modern react applications are done with a framework or Sass, in that case i suggest splitting components with use case and create a index.js in the folder and export all components from that folder
I legit watch your videos to fall asleep. They are useful, and I appreciate them but I sometimes wonder if this is an AI speaking half the time. The silver lining here is that I get regular sleep, so umm... thanks :)
Now I know why I messed up when first trying to build a thing on RN. This framework and Js project really need a simpler structure and easier to manage.
PLEASE MORE VIDEOS LIKE THIS!!! I love code reports and 100 seconds series but wish we got videos like this more often! Keep up the awesome job!!
Rather than creating a custom hook just for storing related state, useReducer can be more ergonomic as it can also provide you with a single dispatch function that can update that state using actions.
As for the second point about nesting; this also comes with a gotcha in that the parent component will update all its children when it updates state that may just be used for a few or a single child. It's useful if child components are reusable, but unnecessary otherwise. It's fine to co-locate state and event handlers in child components and is often easier to reason about; If you truly run into performance issues due to unnecessary re-renders, you can wrap child components in React.memo.
Thanks again for the tutorials Jeff your style of teaching is very straight forward and to the point. I am curious if anyone has seen a similar extension for JetBrains (glean)
Thank you soooo much for glean, didn't know it !! :)
the curried function for event handlers is my new favorite piece of code.
Very helpful video, amazing content as usual
The extension Glean change my life!!!
Jeff is still my favourite tech youtuber
Amazing ! Thanks !
7:36 this is discussed in other thread that it will hurt the performance?
Thanks!
React antipattern #1: AngularJS
Then goes Vue and Svelte...
Ben Awad wants to know your location
React's flexibility is its greatest strength, but if you don't know what you're doing, it can sometimes lead to weird things
That's why more opinionated frameworks like Vue exist, so you don't have to learn every way you can do stuff.
I myself would honestly stick to Svelte for personal projects, it's one of few frameworks that don't actively piss you off on each step.
(And yes, React is a lib - as long as you don't slap JSX on top of it)
@@shapelessed That's why other libs/frameworks like Vue, angular and svelte in the second, third and fourth place
@@amirhoseinhesami9336 react came first and that was huge advantage.. i would go with vueJS or svelte or even angular for complex Enterprise apps. The non opinionated react is not really my thing
@@lahcencodery vue and svelte in the enterprise world is not a real thing and also the funniest joke ever however the "angular" used to dominate the enterprise world however it is not relevant today because react is dominating the enterprise as well
@@amirhoseinhesami9336 backed by Google and Facebook/meta 🤷🏻
Any other reason which is better!?
to the people who still use classes components: make sure to keep cleaning your caves, bad environment effect the productivity of the developer.
I just got accepted as a frontend dev on a startup company. A year ago, CEO hired some devs to create mobile app and web app using react native. Devs finished the contract and left.
And this is where i get in. Imagine me, a react newbie, who have to fiddle with a messilly coded and stinky class based component react app. The worst part is, there's almost zero class based component tutorials on youtube.
At least the pay is nice
@@user-yy3ki9rl6i I'd avise you to rely on the React docs, fortunately they have an excellent documentation (which is actually rare), and with plenty of class-based examples. And try sell your boss a progressive refactoring of your code.
i remember when my team first work on React before it got hooks but 3 months later, hooks got introduced and people didn't want to jump ship. tried convincing others to move all to hooks, but too late. we end up half of the code in hooks
@@user-yy3ki9rl6i
the majority of react developers stop using classes and try to avoid it. because functions give almost the same result and with more readable and clean code. classes still has some render cycle methods that are not exist in functions but you will not need them in 90% of the cases.
@@user-yy3ki9rl6i I set aside an hour every workday to refactor one or two class components into hooks-based function components. A week of that taught me more about the codebase than the previous two months, and after two weeks my boss took me aside and asked me to refactor everything. Refactoring to hooks is such a win in performance and complexity that you should try to make it happen however you can, everyone around you will notice the improvements quickly
Great video! When you work with react every day for a few years, you slowly realize exactly the things you showed here. It would've been nice to see this 2 years ago :)
I think that when you have prop drilling issues, before reaching for context or redux, it's usually best to consider if you are using the `children` prop effectively. A lot of the time if you aren't using the drilled prop in the intermediate components, they can render `{children}` and that prop can be passed directly from the origin parent to the component that needs it.
Thank you. This is great.
And it always more flexible. For free.
Sorry I don't understand this. Can you explain it a bit different?
@@Bobobratwurscht You have a parent component and a child component. The parent component accepts a bunch of props which are just used to pass (or drill) it to the child component. What you can do instead is to just accept a children prop in the parent component and render it. When you now render the parent component, you pass the child component as the children prop of the parent.
@@Dekatelon I'm still not following.
Very important thing with context - any item that consumes that context (i.e., the `const count = useContext(CountContext);` in the example) will ALWAYS rerender when the context value changes, regardless of if that component actually uses that value or not. A very common pitfall is to use Context as a sort of 'big store', where you've got a ton of values in the context that are consumed by components that only need one or two of said values. This means that every time the context component updates, EVERY SINGLE CHILD COMPONENT THAT RELIES ON THAT CONTEXT WILL ALSO RERENDER. It's a huge, huge performance issue in very large apps.
Keep context to items that will change extremely rarely - themes, authentication states, etc - and never use them for data that changes somewhat frequently unless you're making a very tiny app that won't see the exponential performance loss of this.
If you need something passed down but don't want to go through the whole heavy mess of Redux / MobX / etc, minimalist state management libraries like Recoil, Zustand, and Jotai are very easy, approachable, and lightweight ways to do this the 'right' way.
But why even have this problem in the first place why is sharing info in react so awful in every way possible
using useMemo to prevent re-renders is a much more minimal approach as you don't need to install any dependencies
great notice thank you
@@feritperliare2890 do you mean why react re-renders? if so, it is a way of keeping application UI updated as the state changes.
@@adeleke5140 yes that’s how react does it meanwhile other frameworks only re render what needs to be re rendered when you call the info somewhere and not every spot that your store somehow reaches its a stupid expensive way to make sure your UI is updated
Some of these are anti-patterns as well. Spreading props is an anti-pattern because it is not declarative and it can cause unneeded exporting of types between components. Additionally, your curried function should be nested within a useCallback() to prevent extra re-renders. If you want to teach against anti-patterns, it would be better if you taught your audience eslint recommended settings for common plugins.
What are those eslint recommend settings?
I agree with the second half but not so much as the first. Spreading is a fine pattern if you as the developer are aware of what you are doing. Not to mention typescript ensures you use it properly
@@_guru ESLint has a bunch of default rules, but if you really wanna give it a go, try the Airbnb rules. Those are opinionated, and I enjoy them very much.
Spreading props isn't an anti-pattern, there's a major difference between personal code style and actual anti-patterns
Callstack's eslint-config package is really nice to use. Not a big fan of AirBnb rules though.
Another anti pattern is doing component updates on unmounted component resulting to memory leaks. Majorly caused by asynchronous Javascript
☝️☝️☝️Thanks for your feedback
@@chatmeup8917 not actual firebase
Many people forget to use useeffect's cleanup function!
when fetching data, the AbortController (native API) can be used, or a library that abstracts this away or avoids this issue can be used, like react-query
calling an async function without setting the state would not lead to memory leaks right?
**looks at the video title** anti-patterns of react.... 😑 Use vue or svelte 🤷🏻
Your videos are addictively informational... Somebody save me from this guy 😂
This video just made me very happy that I work with Svelte...
It is inevitable. React will die eventually. Long live Svelte!
It's funny enough you are happy with Svelte but watching video about React patterns :D
@@yevhenkozlov286 It's like watching videos of life in Africa, that make you appreciate what you have.
edit: apparently currying is still the correct term, i've just never ever seen it used for general function generation.
regarding 9: in the example that _you show_ it's a curried function, but what _you describe_ is just a factory function.
curried functions basically let you specify the multiple arguments of a function A in multiple steps where each step or function call returns you a function where that value is "stored" in the closure and you can specify the next argument with the next call on the returned function.
Which is better in terms of implementation though? Factory or Curried? Because they're technically the same...
@@creatorsremose they're not. currying means the final function arguments get composed in this staged fashion. every curried function is a function factory, but function factories don't have to receive or provide any arguments up or down the chain. when working with react, you probably never need currying.
When would you need currying?
@@BuyHighSellLo it's a functional programming pattern for when you have a target function with more than one argument. if you look up currying you should find good examples.
He is correctly describing a curried function. Also, factory functions return objects, not functions (unless we're being strict with how we define a function in Javascript).
Many people are asking about vscode settings. According to me :
Font : Fira Code
Theme : One Dark Pro
Hey, I've actually thought of using curried functions, but my initial thoughts tell me that it is going to going to consume more memory as for each call, a new big function will be made again to be called. In contrast, the one without function currying I suppose would call the same function, not create a new one, but with different params, hence better perf and memory. I have yet to test if this is true or not. Is that how it works in JS? I'd like to know the results for this.
Doesn't matter. With curried function on 3 calls you create and return 3 functions. If you use 3 arrow functions, you created them as well, but manually, not programmatically.
I don't think that's the case. See, what you're thinking is that the onChange function runs the currying on every call, but what it does is that each call runs the returned function. The curry function only runs on re-render.
@@isqueirosbic Idk if you were responding to me or Nathan, but let me make it clear:
In both cases on each render you create three functions that live in memory. In the first example you create them manually writing three arrow functions. In the second example you create those three functions by running the "creator"/"factory" function.
In the second example you have "more calls" but that doesn't matter. The memory footprint is close to being exactly the same.
@@CzajekTutorialowiec I was answering nathan ;)
In either case, it creates 3 new functions on every render.
If you *really* want to try to avoid this, you can create a useCallback function but this is most likely overkill over-optimisation.
const handleClick = useCallback((param) => (event) => clickHandler(event, param, state), [state])
Button text
One of these for Angular would be amazing! Great video as always Jeff
Angular is dead (This comment was paid for by Ben Awad)
@@invinciblemode AngularJS to be exact, killed by google since December last year
Eh, that would probably confuse most Javascript viewers who've never heard of types lol
@@niklasstahl98 Not really. Most JS developers with a little bit of experience will be familiar with the fundamental types. It's only jarring for the first couple of days using them in a strict manner but after that it becomes natural.
The "prop plowing" technique is great but I tend not to do it much because TypeScript won't validate the input against the component's input props
TypeScript, deservedly, gets a lot of praise, but it's really under-discussed how much you have to change the way you code in order to use it properly. I think it's lighthandedness is pretty overstated
I believe TS validates spreaded objects `{...childProps}`, but it might only work if the object created was typed explicitly.
@@teacul I personally don't try to fight it too much, it's an addition here to simplify our lives but if it ends up becoming cumbersome that's not a great deal anymore
WHAT, I always create children with a function IN the component, without props. Oh my god, I feel so stupid now. Time to refactor and test the performance I guess
If you curry a javascript function in es6, you dont' need the braces and return statement, you can double up on the arrow syntax:
const handleIt = v => e => console.log(e, v)
equivalent function to the one shown at 7:31
True, but this also comes at a cost of readability
Talk about antipatterns
He uses TypeScript so if you want to define a type for the parameter you need to use parentheses
I hate this syntax with a passion. I use regular function declarations for named functions and arrow functions for callbacks
This is by far the most efficient way to learn code and environment optimization I've seen. Every language needs a video like this, amazing work!
The biggest anti-pattern is using React in 2022. Svelte and even Vue is thousands of times better in everything.
Svelte is a godsend!
Shouldn't the useMetadata hook return a set function as well? Otherwise That wouldn't work would it?
For subscribing to state, it's ok. But you're right that if you need to update state, you'd need a way to provide those dispatch functions. An alternative is to use useReducer instead, which gives you a single dispatch function that you can use to update state through actions.
@@dealloc hahaha to state
Prop drilling is made a bigger issue than it really is. If you're drilling more than 3-4 levels deep then you have an architectural issue, not a state issue. Redux causes more headaches than prop drill itself.
Another useful feature "functional state update"
if the new state depends on the previous state, you can pass a callback to setState like
`setState(previousCount => previousCount + 1)` instead of `setState(count + 1)`
Using functional state update will help in the memoization of the event handler using `useCallback` as the dependencies can be an empty array
and it will also help in avoiding stale state closures
Always followed it to save myself from trouble
i use for handleinput functions
Yeap..it is a known issue. Everytime you need the current state value always use the callback. You can even end up in weird bugs if you the state value gets stale (like in an interval)
I remember seeing this in a PR and was very confused.... Now I use it all the time
setState(count++) ; )
Cool. Now imma copycthisvpaxksge over to SolidJS cuz I like SolidJS better than React.
9 months later and I can finally understand this video! First time I watched it, I had no idea what any of this was.
"... that leaves us developers with plenty of room to screw things up with our own stupid ideas." So underrated.
Ok, glean was a blessing from this video. I did not know it existed lol. I used rfc and rnfc, but this is next level. Thanks man!
React's flexibility comes with great responsibility. I once worked on a React project where everything is memoized. We thought it would improve performance, but lately I realized it was a premature optimization
Definitely a problem I see often. Using memo/useMemo/useCallback is a tradeoff between spending processing time and memory. JavaScript engines are really fast nowadays, and React isn't slow either. For most UI you won't notice any performance issues unless you do something really complicated; at which point you have a few options;
If your component does something that results changes the DOM or needs to do offload rendering where it doesn't matter whether React can keep track of it, you can use imperative APIs; e.g. for animations. You can use refs to grab the context of underlying DOM nodes of React elements you want to access.
In most cases, splitting out components into logical parts that can do their own work, such as subscribing to specific state or doing computationally expensive things that aren't easy to optimize otherwise, you can memoize it, optionally with a comparison function. The less props you pass those expensive components the easier it becomes to manage at the cost of less reusability-again a compromise you'll have to make.
Using Svelte fixes at least some of these ;)
☝️☝️☝️Thanks for your feedback
And probably introduces other ones, having to rewrite your entire codebase for one ;). All have their pros and cons, much more useful to figure out where to use one or the other.
@@Nemcoification Well worth the effort. I'd rather rewrite the whole thing than deal with all the useGoFuckYourself bullshit.
I am using Svelte exclusively, but the concepts here in React still apply when it comes to componentizing. Super useful advice, thanks!
Svelte saved my fucking life. React is garbage in comparison.
0:12 There is no way into that maze with the entrances in front of that guy lol. One leads straight back out and the other is a dead end. Unless the one that leads straight back out is the solution.
As a svelte user, I sometimes watch react tutorials. Just to feel superior.
React is awesome. Screw svelte
Just installed glean. Thanks for the tip!
this video temporarily cured my impostor syndrome as I knew and do all of these. thanks, Jeff!
No to file barrelling. Just use the path - you're going to affect bundler's ability to tree shake.
could you elaborate or post it a link about this?
for the context API i like to use this pattern where i have a single file that
- creates the context with the default value undefined, but does not export it
- creates and exports a provider component
- creates and exports a custom hook that uses useContext and throws if the context value is undefined
this way you always only import one thing (useMyContext hook) and you'll also always immediately know if you're using a component and there's no provider in it's parent hierarchy.
Interesting….where can I learn this method?
@@shawnc7381 on your own 🤣. Just understand the context API and custom hook deeply 💯
@@shawnc7381 it's really nothing more than i described in the comment :D
@@shawnc7381 I can't post a link here, but google "kent c dodds how to use react context effectively" there's a post on his blog that covers this pattern.
Ben Awad watching this video - 😃😃😃
Ben Awad at 4:18 - 😐😑😡
Stop posting, this was your 420th video
Zustand in 100 seconds please. As always , great video. Thanks for your time.
In react everything depends on the developer’s knowledge, it can get to a complete mess or a solid structure. Great video 👍
Just a little bit more relaxed narration and it would be perfect. And a breather between each section. If you are only listening, it's hard to know when you start talking about a different thing.
Exactly.. good content but hard to grab
Your videos are amazing man. Whenever I need a quick refresher you're the go to! Really appreciate all your hard work.
While I do agree with basic tricks, I don't agree with some of the points you made;
1 - While big components are harder to read, extracting a component just for the sake of it is also a bad experience, which I consider an anti-pattern. Like Nav that you show there, if you are not going to reuse that component ever, there is no point of extracting it. Long trees of HTML is nature of the web, you can't escape from it, what you essentially do there is hiding it. While this might come in handy in some situations, I don't think this is a go for everything, usually not worth the complexity if it doesn't have an internal state.
5 - I strongly disagree with this. I don't know if you ever take over on a project someone else made with file per function/component. I did recently, 2 times a row. It takes so much time to get into project, figure out what's what. Usually people doing that cross reference everything from eachother, which makes you hop from file to file as everything references everything. This approach is popularized by companies like Facebook, for the case of React, to take advantage of their monorepos and cross-use functions/components between files. If you are not at the scale of Facebook, I don't think that's necessary.
I do categorize my components as unique and generic. If it is something like a button, or input, table etc., which is used multiple times in different place, *with different props*, that's a generic component for me. Sure, I do create their own files for them. They don't cross reference except in several cases. So it isn't like matryoshka, you don't find another component hidden inside another, which was hid inside another and so on. If a component is unique, like a section of page, having a purpose, specific state and so on, I do put them into another folder, each into their own files. One important thing here is, if those components require child components to render, I do define them on the same file (though I don't export them, they are internal). This helps much to reduce files I need to name and traverse.
For functions, I tend to put lots of related things into big chunks of files. If it becomes too big or there are specific kind of functions piling up, I do seperate them into another namespace. But doing function per file is quite overkill for me. So I'd say it is a balance between piling everything into same file vs putting everything into their own files. I was doing the latter 2 years ago, which become a maintainance hell for me quickly, so reduced it and happy with it, so I consider it an anti-pattern.
7 - Redux isn't for prop-drilling, as you say it is overkill, but I wanted to emphasize it.
Other than those, nice video. I do remember a video of you comparing some React code, which I commented about anti-patterns in that video; happy to see that you are using React extensively and creating React courses!
React itself suggests to use `containment` or `composition` first before even considering the react context API: reactjs.org/docs/composition-vs-inheritance.html
id say avoid context if it's not global. any state management is difficult to do testings and reusability, esp we are using Nx atm
Yep. For some reason, I've found that new devs latch on to the "prop drilling = bad" concept pretty quick, and they reach for the context API first. An explosion of random grab bag contexts ensues...
@@godoftheLTD Indeed. Context comes with its own tradeoffs that are easy to miss; especially if you use it for anything else but dependency injection.
Contexts can be useful for isolated component trees that needs shared values deeply. But for global state management, it's often better to use state management libraries that are optimized to avoid unnecessary re-renders. In most cases passing props down 2-3 layers is fine.
Spreading props is one of the worst anti-patterns - it makes the code unreadable and a lot of the time you'd have to guess what was passed there.
Very helpful as always. As someone just getting back into coding after a break these help a ton. I'd love to see one over Tailwind CSS
Why did you take a break if I may ask?, Was it due to a burnout or something like that?, I'm just curious so you don't have to answer if you don't feel like doing so :).
@@daumienebi I started a marketing and business development company. So for the majority of my time doing other things. I still built websites and coded it was just in WordPress more than anything so mostly code snippets and changing things in a theme. Recently, my company has grown to the point where I can spend some time doing new things and I picked up design and software development a lot more!
@@ChristianHelmsOther ohhh okay, congratulations on your Company!!
@@daumienebi Thank you very much! It's been a blast
I really miss your Angular tutorials. 😔
Would be nice if you could give this framework some love again.
But nice video nonetheless!
"It's called prop drilling because it makes you want to drill a hole in your head" - Jeff 2022
In number 9 while technically correct there is a pretty decent size caveat. React 16 and 17 will batch setStates as long as it not in an async function. If you are in an async function you can use unstable_batchedUpdates to batch setStates. The latter being pretty hacky in my mind, but can save you from a large refactor
Am I the only developer who hates react? I know it has it's place, but every time I see react code I just cry at the performance loss and the junior devs do whatever in react because the state is managed for you!
Your videos are noisless, consice and fire 😄
I love you. This was amazing. Please do other technologies in the same way. Angular, rxjs, firebase? :P
Did you just reuse the thumbnail?
*EDIT:* NVM, it's a series.
For real.. How do you do that? Im learning React and googling antipatterns just when you post this. How?
Time travel.
Man you are a genius. Your channel and then 10 places are empty and then everyone else, it's amazing how original you are with content and just keep going! Big greetings from Serbia! :)
☝️☝️☝️Thanks for your feedback
Great video! I need this course for my start up project im currently working on.
A masterclass in both react and instructional videos. Thank you!
Just curious, why does the course choose to cover react final form over react hook form?
For the currying comment, rather than having a function outside of the component, use a useCallback or with every render it's producing a new function which then means when you're passing that as a prop it's seen as a prop change and causes a re-render for those components
Chapter 1 1 In the beginning God created the heaven and the earth. 2 And the earth was without form, and void; and darkness was upon the face of the deep. And the Spirit of God moved upon the face of the waters. 3 And God said, Let there be light: and there was light. 4 And God saw the light, that it was good: and God divided the light from the darkness. 5 And God called the light Day, and the darkness he called Night. And the evening and the morning were the first day. 6 And God said, Let there be a firmament in the midst of the waters, and let it divide the waters from the waters. 7 And God made the firmament, and divided the waters which were under the firmament from the waters which were above the firmament: and it was so. 8 And God called the firmament Heaven. And the evening and the morning were the second day. 9 And God said, Let the waters under the heaven be gathered together unto one place, and let the dry land appear: and it was so. 10 And God called the dry land Earth; and the gathering together of the waters called he Seas: and God saw that it was good. 11 And God said, Let the earth bring forth grass, the herb yielding seed, and the fruit tree yielding fruit after his kind, whose seed is in itself, upon the earth: and it was so. 12 And the earth brought forth grass, and herb yielding seed after his kind, and the tree yielding fruit, whose seed was in itself, after his kind: and God saw that it was good. 13 And the evening and the morning were the third day. 14 And God said, Let there be lights in the firmament of the heaven to divide the day from the night; and let them be for signs, and for seasons, and for days, and years: 15 And let them be for lights in the firmament of the heaven to give light upon the earth: and it was so. 16 And God made two great lights; the greater light to rule the day, and the lesser light to rule the night: he made the stars also. 17 And God set them in the firmament of the heaven to give light upon the earth, 18 And to rule over the day and over the night, and to divide the light from the darkness: and God saw that it was good. 19 And the evening and the morning were the fourth day. 20 And God said, Let the waters bring forth abundantly the moving creature that hath life, and fowl that may fly above the earth in the open firmament of heaven. 21 And God created great whales, and every living creature that moveth, which the waters brought forth abundantly, after their kind, and every winged fowl after his kind: and God saw that it was good. 22 And God blessed them, saying, Be fruitful, and multiply, and fill the waters in the seas, and let fowl multiply in the earth. 23 And the evening and the morning were the fifth day. 24 And God said, Let the earth bring forth the living creature after his kind, cattle, and creeping thing, and beast of the earth after his kind: and it was so. 25 And God made the beast of the earth after his kind, and cattle after their kind, and every thing that creepeth upon the earth after his kind: and God saw that it was good. 26 And God said, Let us make man in our image, after our likeness: and let them have dominion over the fish of the sea, and over the fowl of the air, and over the cattle, and over all the earth, and over every creeping thing that creepeth upon the earth. 27 So God created man in his own image, in the image of God created he him; male and female created he them. 28 And God blessed them, and God said unto them, Be fruitful, and multiply, and replenish the earth, and subdue it: and have dominion over the fish of the sea, and over the fowl of the air, and over every living thing that moveth upon the earth. 29 And God said, Behold, I have given you every herb bearing seed, which is upon the face of all the earth, and every tree, in the which is the fruit of a tree yielding seed; to you it shall be for meat. 30 And to every beast of the earth, and to every fowl of the air, and to every thing that creepeth upon the earth, wherein there is life, I have given every green herb for meat: and it was so. 31 And God saw every thing that he had made, and, behold, it was very good. And the evening and the morning were the sixth day.
Great video! It’s crazy to me though how many of these patterns are encouraged out of the box with something like SvelteKit. First principles approach with a clean slate has done the Svelte team wonders.
That Currying mentioned....which will impress your Friends and family😂😁...
Great Videos bro..😍😍
Nice video! Can you do a "Code This, Not That!" video for Angular?
"10 Vue Antipatterns to Avoid" Please.
☝️☝️☝️Thanks for your feedback
And when your app gets even bigger and unmanageable, throw react away and start using angular 🤗❤
What's the difference between "useMemo" and "useeffect" on data change?
Awesome, educational video! Really appreciate the effort (and also the humor) that went into this. Also, this is the first tutorial video I watch on default speed and not 1.5x 😅
Damn! I already use all these best practices! I must be a pro then XD
☝️☝️☝️Thanks for your feedback
My biggest struggle with react was trying to change the state of a parent component within the child component
Send the setstate with the state as a prop to child component and thats it.
react hooks made this thing very easy just send the state and setState as a prop and basically thats it
As these fine gentlemen suggested, you define a ```[state, setState] = useState('foo');``` inside your parent component. Then you pass the setState function to the children like so ``` ```. Within the child, you ```function Child({ state, setState }) { ... }``` and you can now use the setState defined in the parent component within the child component, to update the state in the parent itself. BTW, *use names with proper semantic meaning*, because "state" means nothing. Think of yourself 15 days later trying to remember what that variable was supposed to store.
You'll end up with prop drilling. Try Context
@@3_smh_3 I’ve done this before and it can result in loss of referential stability. This leads to unpredictable behavior and excessive renders. The child will Render multiple times whenever the parent does as that function recalculating its value counts as a “prop change”
If you want to encapsulate it, you can avoid this by wrapping the function in a useCallback hook and including the new value inside the dependency array.
Please do this for Angular as well!
Angular antipattern #1: using angular
no.
Angular is a bit harder to mess up because it gives fewer freedoms than react
I went from junior to confirmed in 8:55
Context is not only "cool" to prevent prop drilling, is very helpful to separate state logic for a bunch of components
is an antipatern. Use instead. The Config type should be declared using TypeScript.
Unfortunately, in my humble opinion, THIS IS THAT. React is the worst web framework compared to the others. Common patterns and functionalities that should be transparent, automatic, and a developer should not worry about them when coding a solution because they must be present in any web app, with React you need to care about all the time and manually repeat in any component code. That results in useless work (not focused on the solution itself) and tons of workarounds to deal with React issues.
Unfortunately I'm learning React because there are no Vue jobs where I live... I don't like the fact that I have to use a lot of libraries with it to make stuff minimally manageable without being a pain in the ass (form handling, two-way data binding, etc...).
Microsoft Edge found the ultimate React anti-pattern: stop using React (for simple UI+data situations like app settings)
i know i'm late to the party, but this is a lot to do a few simple things. I am coming from vue and needed to see habits for react development. no offence though, I think both get the job done, but react is more common in this region. That refactor markup -> component thing is really good.
I love your videos, but please, do not include images that may affect people sensible to gore. People who undergo brain surgery often become very sensible to such images/videos. That drill was unnecessary. Love your content. Cheers
if you want to do props spreading but be more explicit about it, you could do ``
HOLY S**T glean is amazing!
thank you for letting me know about this! this was a dream for me
Imagine if you just had something like rxjs and behaviourSubject at your disposal 😅 instead of prop drilling…
Обращаюсь к российским айтишникам. У вас забирают лучшие года жизни. ua-cam.com/video/tzLSfWGl76A/v-deo.html
Which extension is better? VSCode React Refactor or Glean? They have a similar number of downloads.
Please Please Please remove 9th Curry section! this is a huge performance anti-pattern!!! The function returning new function always, and component which is using this returned new function will re-render together with parent component all the time! You have to use useCallback on functions before passing it to the prop, and you can't use useCallback on curried inner function!
7:31, I couldn't think of that. I was at least familiar with some coding tips you have provided until 7:31 as i am watching, but i knew that i can return a function.
So basically Angular is still the greatest of all time 🎉🎉🎉
Re: the currying example, I'm not a big fan of coding "to impress my friends and family" haha. I'd rather it be as simple and unimpressive as possible.
5. That only works if you style your components with plain css, however most modern react applications are done with a framework or Sass, in that case i suggest splitting components with use case and create a index.js in the folder and export all components from that folder
☝️☝️☝️Thanks for your feedback
I legit watch your videos to fall asleep. They are useful, and I appreciate them but I sometimes wonder if this is an AI speaking half the time. The silver lining here is that I get regular sleep, so umm... thanks :)
Now I know why I messed up when first trying to build a thing on RN.
This framework and Js project really need a simpler structure and easier to manage.