How I Write Clean Code in React

31.54k views3722 WordsCopy TextShare
Cosden Solutions
Check Out Brilliant → https://brilliant.org/CosdenSolutions 🚀 Project React → https://cosden.solu...
Video Transcript:
In this video, I'm going to walk you through my  process of writing clean code as a senior React developer. This process has basically been built  over eight years of experience, and hopefully it can help you write better code. And also, if  you want to learn how to build a big and complex application with React as a total beginner, check  out Project React in the description.
So over here, we have a simple React application with a  simple component, and we have your profile IDs, which is a static array of numbers. We have one  all the way through five. And then we're taking those IDs, we're mapping over each one of them,  and then for every single one, we're rendering a simple anchor tag, and we're redirecting to slash  profile slash ID.
Now our task is to actually build out the profile page that this link is  going to send to. And through that, I'm going to show you my process of approaching this and how I  write clean code, and we're going to do it in very few lines of code. So the first thing that we're  going to want to do is come here to our sidebar and create a new folder, because this is an empty  project.
We currently don't have a folder for all of our page components. So we're going to come  here, make a new folder, we're going to call this one pages. And inside of it, we're going to make a  new file.
And we're going to do profile page. tsx, like so, create it and then open it. In here,  we're going to do rgsfc.
For a shortcut, we're going to do profile page. And then we're just  going to put a div over here. And now we're going to close this what happened, there we go.
Why is  this always so much more difficult than I want it to be. And in here, we're going to put the content  for our actual page. Now I'm keeping things simple for the video, we don't actually have any routing  solution set up to actually render this page on slash profiles.
But you can use your imagination.  That's not the point of this video. The point of this video is to teach you how to build this  component and the other components.
And more importantly, how to approach building them. So  the first thing that we need in this component is probably some styles right for the general  page. So we're going to come here and do class name.
And we're going to do container and then MX  auto. What this is going to do is this container class here is going to set a max width for this  entire diff. And the MX auto is going to make sure that this is centered.
Now the thing about the  styles over here is I wouldn't put them directly inside of this profile page component, because the  truth is, in reality, in a real project, you're most likely going to have other pages in your  application. And they're most probably going to want to also have the same styles over here. These  are more technically called the layout styles than specific styles related only to the profile page. 
So instead of doing this, what I would actually do instead is I would come here to my sidebar,  and I'll do a new folder here, because again, we don't have a folder for components, we're  going to do components. And in here, I'm actually going to do a component. And we're going to, I'm  actually going to do a component, we're going to call this one page layout.
tsx, like so. And in  this component, we're going to put these exact styles. So let's close the sidebar, let's come  over here.
And let's take actually all of this, because this is going to be pretty much the same.  Let's go back here to page layout, rename this to page layout, so page layout. And then we're going  to have this component taken children as props, we're going to put these styles over here, and  then wrap the children with this diff.
That way, we can use this for any page in our application,  and always get the same styles applied. So we're going to come here and we're going to do type  page layout props. And that is going to be props with children.
And we're going to import this  directly from React. Let's keep things simple, we're not going to have any other props over  here. And then we're going to do here, children, children, and then page layout props like so.
And  then we're going to pass these children directly inside of the div children like so. Now we have  the page layout component, we can come back here to the actual page, remove these styles, because  we're not going to need them. And then instead of this div, we can directly do page layout,  import this from components slash page layout, and then put our content over here.
For example,  we're going to put h1 profile page like so and remove the space. Now we did the same exact thing  as we had it before. But we've extracted all of the layout styles inside of a separate component. 
And we can actually use that component in here in the profile page and any other page that we have  in our application. This is also really useful in the case where you might want to add different  things to this page layout. For example, in a lot of cases, you're going to have a nav bar component  over here.
And if we save, we might also have a footer over here as well, right, these would go  inside of the page layout, because you don't want to have to import and put all of these components  in every single page. Even worse, if you want to change how these are displayed, maybe this gets a  wrapper div or something with some styles, you can put them once inside of this component. And then  every page that uses this component automatically gets the same exact styles.
This makes it much  more cleaner. And it's much more scalable to do it this way. Now here's the thing, what we're  currently doing right now inside of this video is something called learning by doing right, I'm not  just telling you and showing you theory and just boring you with that, I'm actually showing you  how it's done.
And more importantly, I'm helping you understand why we do it this way, instead of  another way. And that's great, because that is also what the sponsor of today's video Brilliant  also does. So Brilliant is a place where you learn by doing with thousands of interactive lessons  in various topics such as math, data analytics, AI, and more importantly, for us programming. 
Brilliant has a learning platform that is designed to be uniquely effective. Each lesson on there  has you solve problems using a hands on approach that lets you play and get a feel for different  concepts, which actually has been proven to be a method six times more effective than just watching  simple lecture videos. Plus, all of the content on Brilliant is crafted by an award winning team of  researchers and professionals from places like MIT, Microsoft, Google, and more.
The great thing  about Brilliant is that it really helps you build critical thinking skills through problem solving  and not memorizing. So while you're building real knowledge on specific topics, you're also learning  how to be a better thinker. And it helps you do all of that in just a couple of minutes a day  with really fun lessons that you can do whenever you have the time.
It's really the opposite  of mindless scrolling, and it really builds a great habit. They actually have some great  courses such as thinking in code, which follows what we're doing in this video and teaches  you solid foundations for computer science, which will help you actually become a better React  developer. To try everything that Brilliant has to offer for free for a full 30 days, visit  brilliant.
org slash cause and solutions, or click the first link in the description.  You're also going to get 20% off an annual premium subscription. Thank you once again to  Brilliant for sponsoring this video.
And now let's continue learning about clean React code.  So now we have to profile page, this profile page is going to receive an ID. So we're going to come  here, we're going to do type profile page props, that is going to be a simple object with  profile ID.
And that is going to be number, let's assume that this ID somehow gets passed  through our navigation solution, which again, we don't have on setup user imagination. Here,  we're going to do profile ID, and we're going to do profile page props. Now we're going to want  to use this ID to actually fetch the data of that profile, because the ID obviously isn't enough. 
And then we're going to want to display the data inside of this component. So to do that, we might  do something like this const, and then profile data, set profile data, and then use state, we're  going to define this to undefined for now. And then depending on how you do this, you might  use react query, you might do something else, we're just going to do it in a simple use effect,  because it's sufficient for this video, we're going to do use effect.
And then we're going to  call this a function, we're going to give this a dependency array, which is going to be profile ID.  And inside of here, we're just going to do const fetch profile, profile equals a sync function.  And then here, we're going to do a weight and then fetch slash API slash profiles.
And then we're  going to pass your profile ID like so. And then we're going to actually we're going to need the  response or const response equals a weight, then const data equals a weight, and then response dot  JSON. And finally, we're going to do set profile data.
And we're going to do profile actually data  and set the data inside of our state. And finally, we're going to call fetch profile. And we're  going to fetch profile.
And we're going to call this function directly inside of the use effect.  So now again, this is a very simple example. But essentially, you have some code that is going  to fetch the data based on this ID, and that is going to set it in some state.
Now, this is all  well and good. And this will work, this is going to fetch the data. And then obviously, it's not  handling loading and error states, which again, it's fine, it's going to set the data inside a  profile data.
And then we can use it directly in this component. But again, I wouldn't do it this  way. This is not clean code.
The thing is, this code shouldn't be long inside of a page component,  a page component, its only responsibility is to take all the different pieces of code and things  that are available across the application, put them together and actually built what it is to  actually be the profile page. It's not responsible for actually implementing the details of those  specific things like this fetching, for example, it should just pull something that fetches the  data instead of implementing the data fetch itself, if you get what I mean. So instead, what  I would do is I would come here to my sidebar, and I would create a new folder inside of SRC.
And  we're going to call this one hooks like so inside of here, we're going to create a new file, we're  going to do use fetch profile dot ts, we're going to close this open up use fetch profile. In here,  I'm going to export one simple function export function, use fetch profile. And this one is going  to take profile ID, which is going to be of type number.
And in here, we're going to put the same  exact code as we had over here, we're going to take all of this code here. And we're going to put  it directly inside of use fetch profile, which is a custom hook, we're going to come here import  use state, we're going to come here and we're going to import use effect. And finally, we're  going to return profile data like so the benefit of doing it this way is that now we've extracted  all of the logic of actually fetching a specific profile based on the profile ID in a separate  component.
This makes it reusable and makes any component that actually needs to fetch the profile  just have to import this use fetch profile hook. And it also removes the responsibility of profile  page to actually implement the details the actual implementation of fetching a user's profile. And  then going back to profile page, the only thing that we have to do is we just have to do const  profile data equals use fetch profile import this from adhook slash profile, and then pass  it profile ID like so.
And now we have the same functionality, we have the same profile. So now we  have profile data over here, we're actually going to want to do something with profile data. Let's  say we want to actually use it here, profile data, and profile data contains some things that we  want to put inside of this component.
Again, I wouldn't do it this way, because once again,  it's not the responsibility of profile page, to actually have the code that implements the UI  of the profile data. Instead, what I would do once again, is I would come here inside of components,  and I would create a new file, and I would call this one profile data dot tsx, like so, and put  all of that logic inside of a separate file inside of a separate component. So here, we're going to  do our jsfc, we're going to profile data, and then we're going to return for now empty, you can just  let's see what happened, you can just imagine that this will do something cool with profile data,  right.
And then here, we're just going to have this type profile data props. And that is going to  be an object, it's going to return data. And we're just going to put any for now, because we actually  don't have any types, it doesn't really matter, we're going to do here this, and we're going  to put profile data, profile data props, like so.
Now we have a separate component called  profile data, which takes in data over here, which can be used to actually do something cool  with profile data and actually show the UI of the profile data. Then once again, we're going to come  back here to profile page. And instead of putting profile data like this, we're going to remove  it and we're going to do profile data, import this from components slash profile data, and we're  going to pass data over here as profile data like so and close this component.
Now we did the same  exact thing as we did here with this custom hook, but we did it with a custom component. Instead  of having the profile page be responsible for implementing the logic of displaying profile data,  we can actually create a separate component, pass it the profile data and have that work that way.  The reason why you want to do things this way, whenever you're building react applications is  that now look at profile page and how small it is, right?
And we actually have a lot of functionality  here, we're fetching data directly. So we have a whole fetch system that is part of this component  that we just have with one line of code, then we actually have layout and styles, we actually  have if I remind you over here, we have a navbar, we have a footer directly inside of this profile  page over here. And we actually have the UI that displays the profile data, all with that with  like 10 lines of code, nine lines of code, actually, this is how you write clean code  in react.
And then profile data over here, you can imagine that this component would also  make use of other components. For example, let's say that we had a part of it that was the  something like the avatar component, right? So we're going to do avatar and close it like this,  you can imagine that this would hold the actual profile picture of that specific profile, and  might have some functionality to allow the user to actually edit their own profile might have a  button that when you tap on it is going to pull up a file input or something, and then allow you to  edit the profile, you would put all of that in a separate component.
And not inside of profile data  over here, you would just pass the avatar whatever you need to pass it. For example, I don't know we  can do like profile photo equals and then profile data dot profile photo, photo like this, right? So  now this component will have one responsibility, it's going to have the actual functionality to  display the avatar and any other functions related to it.
And we pass it from here any properties  that it needs to do its functions. If we then had another component, for example, the profile posts,  we can have something like post list, right, which is a list of posts. And we can actually do  something like posts.
And then we're going to do profile data dot posts, like some and pass the  actual post of the profile data to post list, post list would then take those posts would  actually render them would probably defer the rendering of each specific individual post or  another component. And doing it that way, you build really clean code in React. And you build  applications that can scale really, really well.
And then as you do this, you're eventually going  to get to a point where you're rendering actual UI. And that's where you're going to use UI  components. So things like buttons, inputs, text, cards, and so on, you're going to use those to  actually render what is being shown on the screen.
But as you can see, those components usually  don't go directly inside of a page component, we're never going to see an actual UI component  over here. I mean, yes, we have an h1 tag, but we could directly put this inside of profile data  as well, it's completely up to us. But usually, you're not going to see individual UI inside of  this component, you're going to see them either in a feature component, which is this profile data,  which actually handles the feature of displaying a profile data, or in other sub components, like  you could expect to see some UI components inside of the avatar component, like an actual thing  that renders an actual image with the user's profile photo that will go inside of this avatar  component.
If you do it this way, and if you build a habit of splitting things up into smaller  components or custom hooks every single time, you're never going to build really big components  that are super messy. And you're always going to write clean code by default, it's going to be  a great habit for you to learn. And some of you might say that this might be overkill, like why  are we creating a whole custom hook just to fetch this one user profile.
And the thing is, it might  seem like overkill, but it's really not because the moment that you need to use this hook in a  separate place, you're already going to have it created in a separate file, instead of taking the  exact code that you had here, and duplicating it inside of two components that is worse to do.  And you're much more likely to do that if you don't already have a custom hook that is already  created and reusable for you to use. So really, the way that I write clean code and react is I  always follow this approach, I split everything up into different types of components.
So page  components, which have the responsibility once again, to take everything across the application  and put them together and make up what it needs to be the actual page that is trying to  render. And then we have feature components, which go inside of page components, usually that  handle individual features. And those might use other feature components are directly might use  UI components to actually render out some UI.
It's really not that complicated. Actually, what  is complicated to me as ironic as that sound is to actually write complicated code. I don't get how  people write complicated code.
When if you follow a simple pattern of actually delegating creating  custom components, you're just never going to end up writing any complex code ever. And most of your  components are going to look like this. So there you go.
These are some simple tips and tricks  that I use on a daily basis to always make sure that I write clean code and react. I hope that  you enjoyed this. And I hope that this has now made you a better react developer.
And once  again, thank you to brilliant for sponsoring this video. If you enjoyed this video, and you  want to see more videos just like this one, make sure to leave this video a big thumbs up,  you can also click here to subscribe. Or you can click here to watch a different video of  mine that YouTube seems to think that you're really going to enjoy.
And with that being said,  my name has been Darius Cosden. This is Cosden Solutions. Thank you so much for watching, and  I will see you in the next video.
Ciao, ciao.
Related Videos
The Most Important Design Pattern in React
35:04
The Most Important Design Pattern in React
Cosden Solutions
89,980 views
You Are Using useEffect Wrong
14:40
You Are Using useEffect Wrong
Cosden Solutions
35,841 views
My 10 “Clean” Code Principles (Start These Now)
15:12
My 10 “Clean” Code Principles (Start These...
Conner Ardman
257,226 views
This is the Only Right Way to Write React clean-code - SOLID
18:23
This is the Only Right Way to Write React ...
CoderOne
670,755 views
React Query Full Course (With Common Patterns & Best Practices)
32:42
React Query Full Course (With Common Patte...
Youssef Benlemlih
804 views
Cursor Tutorial for Beginners (AI Code Editor)
15:20
Cursor Tutorial for Beginners (AI Code Edi...
Tech With Tim
33,622 views
The Correct Way to Use Form Data in React
17:29
The Correct Way to Use Form Data in React
Cosden Solutions
11,794 views
Zustand with Context API – An Advanced Pattern
19:12
Zustand with Context API – An Advanced Pat...
Cosden Solutions
7,583 views
This Folder Structure Makes Me 100% More Productive
24:36
This Folder Structure Makes Me 100% More P...
Web Dev Simplified
61,800 views
The Best React Code I Wrote (Code Review)
24:50
The Best React Code I Wrote (Code Review)
Cosden Solutions
28,874 views
Modern Data Fetching in React (Complete Guide)
16:41
Modern Data Fetching in React (Complete Gu...
Cosden Solutions
59,971 views
Zod Validation in React (Complete Tutorial)
29:44
Zod Validation in React (Complete Tutorial)
Cosden Solutions
11,161 views
If __name__ == "__main__" for Python Developers
8:47
If __name__ == "__main__" for Python Devel...
Python Simplified
410,317 views
Authentication Flow in Next.js (Complete Tutorial)
30:37
Authentication Flow in Next.js (Complete T...
Cosden Solutions
10,950 views
3 Tips To Write Clean Code (from an ex-Google software engineer)
17:12
3 Tips To Write Clean Code (from an ex-Goo...
Clément Mihailescu
197,304 views
All 12 useState & useEffect Mistakes Junior React Developers Still Make in 2024
46:15
All 12 useState & useEffect Mistakes Junio...
ByteGrad
1,007,034 views
Refactoring a React Component (Design Patterns)
28:20
Refactoring a React Component (Design Patt...
Cosden Solutions
15,786 views
JavaScript Visualized - Event Loop, Web APIs, (Micro)task Queue
12:35
JavaScript Visualized - Event Loop, Web AP...
Lydia Hallie
593,625 views
Refactoring a React component - Design Patterns
15:19
Refactoring a React component - Design Pat...
Cosden Solutions
98,502 views
Combining Zustand with React Query
20:24
Combining Zustand with React Query
Cosden Solutions
23,823 views
Copyright © 2024. Made with ♥ in London by YTScribe.com