10 React Antipatterns to Avoid - Code This, Not That!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Repost from yesterday.........

๐Ÿ‘๏ธŽ︎ 1 ๐Ÿ‘ค๏ธŽ︎ u/notAnotherJSDev ๐Ÿ“…๏ธŽ︎ Mar 03 2022 ๐Ÿ—ซ︎ replies
Captions
react.js is elegant and minimal on the service just write a javascript function to represent a component that automatically renders when your data changes it's simple but also misleading in reality react is a highly complex ui library with a good amount of technical baggage that has accumulated over the last decade many newer frameworks attempt to do things better but react is still the king and if you want to be a web developer in 2022 it's a very good idea to learn it the problem is that react is unopinionated yet provides many different ways to solve the same problems that leaves us developers with plenty of room to screw things up with our own stupid ideas in today's episode of code this not that we'll look at 10 anti-patterns in react along with tips and tricks to improve our code and also prepare for a front-end technical interview before we get started i have an announcement i'm working on a brand new course for pro members that teaches the fundamentals of react in my 100 seconds of code format then puts those concepts to use by building multiple full stack applications from scratch the course is not finished yet but i'll be releasing new videos for it every couple days on fire ship i o when i initially start building a react app i usually start by writing one big giant component often in the app component provided by create react app and that's intentional because i usually don't know how i want my code to be organized initially and i don't want to waste my time over organizing things before i even know what i want to do however this results in an anti-pattern of having one overly large deeply nested component a component like this is hard to understand refactor and test we can improve this code by refactoring into reusable components like this navbar could easily be broken down into one or more components that better represent what it does now that may sound like a lot of work but luckily there's a vs code extension called glean that can leverage the ide to do this work for us install it then highlight the code you want to extract into its own component click the light bulb and you'll see a bunch of options to refactor like render conditionally or extract component and give it a name then it will automatically move the code while including the required props it's a massive time saver that i couldn't imagine living without now when you start refactoring a large component you might be tempted into another anti-pattern of nesting components in this example we've defined a child component that lives inside the parent component the child uses a function defined in the parent and by defining it here we don't need to provide a prop for that function it feels very intuitive and it works perfectly fine but there's a major problem here every time the parent component is rendered it will also redefine the child component which means it gets a new memory address and that could lead to performance issues and unpredictable behavior the solution is to either not define a child component at all or to move the child component out of the parent and pass the function in as a prop this example demonstrates how react is very simple on the surface but if you don't know exactly what's going on it's easy to shoot yourself in the foot here's a similar example of a component that does too much work and might end up causing performance issues let's imagine we have a component with two different pieces of state on one piece of state we need to run an expensive calculation anytime the value changes the problem with our current implementation is that any time the state changes on this component it will rerun the expensive calculation even though it only depends on the one count value it's not very obvious but you have a potential performance bottleneck here in a situation like this you'll want to use the use memo hook what it will do is remember the last value and only run the actual function when its dependent data changes you might also run into the situation when working with functions and for that react provides a used callback hook now another thing you might run into is that when defining a brand new component you get an error when trying to return two sibling elements together that's because every component can have only one root element so what you might do is wrap it with a div that works perfectly fine but it leads to a bunch of unnecessary divs in your markup and that can cause issues with accessibility and css styling to address this concern react has a built-in fragment component or better yet you can use the shorthand syntax of an empty element which tells react to render nothing as the parent element now as your app grows in complexity and you start creating more and more components you'll want to have an opinionated way to organize them a good rule to follow is one component per file it can be tempting to export multiple components from a single file but things will get pretty complicated quickly if a component is going to be exported it's generally best that it lives in its own file now in larger projects i would take things one step further and give every component its own directory if you name the file index then you can easily export it from that directory but inside the directory you can add other files like a css module for example or anything else you might need for testing storybook typescript and so on this is how they do things by default in angular and i find it works really well for large projects now there is one drawback when naming your component index and that's the fact that it's kind of confusing when working with tabs in your ide what you can do is give your component file a regular name then use the index file to export it that's called a barrel and it will keep your imports nice and concise while also providing a readable file name for the ide one of the biggest problems with big complex apps though is that they're big and what that means is that when you ship your app to production it'll have a slow initial page load because it takes a long time for the browser to download the javascript bundle so what can we do about that if you're using a tool like nexjs or create react app which are built on top of webpack it's very easy to implement code splitting normally to import code you use an import statement however browsers now support dynamic imports which allows you to load a module asynchronously using the import function when webpack sees that code it automatically knows to split that code into a different bundle which won't be required until after the initial page load that works fine for plain javascript but not so much when it comes to react components however react has a feature to support lazy loading which is still experimental today but it allows you to use dynamic imports on react components once a component is dynamically imported you can then wrap it in the suspense component to show a fallback ui when it's loading now another problem you might run into with big projects is that you might have one component at the very top that holds your state but then you have a deeply nested component that also needs to use that state what you have to do is then pass that state as a prop to a bunch of intermediate components that don't actually need it until it finally gets to that child this is known as prop drilling because it makes you want to drill a hole into your brain one solution is to bring in a state management library like redux but that's a heavy-handed approach when you have global data that's used everywhere like an authenticated user for example you can share it everywhere with the context api you first provide the data at a certain point in the component tree then any component nested under it at any level can access that data sounds awesome but it does come at a cost the context api is something that you should use sparingly because it makes your components impossible to reuse without having that provider as a parent most apps only have a handful of values that are truly global that stuff can go into context while everything else should be more localized prop drilling is a vertical problem but you might also end up with a horizontal problem called prop plowing which is a term i just made up what might happen is that you end up with components that have a lot of different props and you end up with this long repetitive code where each prop has the same name as the variable passed to it when you have an object that contains all the props that you're passing to the child you can use the spread syntax to pass them all at the same time that makes your code much more concise and personally i'm a big fan of this however it does make your code less explicit so i typically only recommend using it when you have a component with a ton of props that really justifies its use another area where your react code can get pretty messy is with event handlers in jsx what happens is you might have a function that takes the event as its first argument but one or more other values as secondary arguments that means to call it you'll need to break out an arrow function and this can get pretty messy if used in multiple places a cool little javascript trick here is to create a curried function basically it's just a function that returns another function the outer function takes our custom arguments while the inner function handles the event that's passed by default this eliminates the need to define an arrow function for each event not only does that make your code look a lot cleaner but it also gives you a legitimate use case for currying which will impress your friends and family and that brings us to anti-pattern number 10. when working with the u state hook in a component it's tempting to put all of your data in a single object it makes the code look cleaner and may also seem more performant because you only need to call set state once however what you should know is that react 18 will do automatic batching whenever you update the state that means calling set state multiple times in the same function will not trigger multiple re-renders therefore it's not a big deal for performance but more importantly it makes your code difficult to extract into a custom hook in the olden days with react class components it was common to organize your code into smart components and dumb components where the smart components control the data and the dumb components just render ui with props there's nothing wrong with this pattern but nowadays it's easier to just extract your logic into a custom hook what i like to do is build my component with a bunch of different stateful values at first then if things get too complex or i want to use that code in a different component i extract it into my own custom hook which itself is just a javascript function this allows you to treat virtually all your components as dump components while your custom hooks handle the more complex business logic and with that we've looked at a small preview of the different things you can screw up and react check out my full course if you want to learn more about react and here's a special discount for making it all the way to the end of this video thanks for watching and i will see you in the next one
Info
Channel: Fireship
Views: 518,472
Rating: undefined out of 5
Keywords: webdev, app development, lesson, tutorial
Id: b0IZo2Aho9Y
Channel Id: undefined
Length: 8min 55sec (535 seconds)
Published: Tue Mar 01 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.