React Best Practices
HTML-код
- Опубликовано: 9 сен 2024
- In this video I will talk to you guys about my opinion on Best Practices in ReactJS. This is something that is actually personal to each developer, but there are some standards in the industry.
-
🚀 Learn ReactJS By Building 6 Projects: codedamn.com/l...
Please leave a comment on what topic you guys want me to cover next!
-
❤️ Support the Channel: / pedrotech
📞 Tutoring Session: www.fiverr.com...
💻 PedroTech Discord: / discord
-
Social
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
Website: machadopedro.com
Twitter: / pedrotech_
Linkedin: / machadop1407
Instagram: / _pedro.machado_
Github: github.com/mac...
Email: machadop1407@gmail.com
Tags:
- React Best Practices
- ReactJS Clean Code
- ReactJS Tutorial
- ReactJS and MySQL
- NodeJS Tutorial
- API Tutorial
@ 00:57 - Like & Subscribe, Separate logic from display
@ 06:30 - When & Where to use inline lambda
@ 08:40 - Structuring large scale applications
@ 15:05 - ESLint & Styled Components
Bonus - Keep components as small as possible, ideally they should do one thing each.
Please like the video!
Bruh thank you so much!
Is your Counter a component or a hook? Shouldn't it be called useCounter?
yes, It should
Definitely it should. It is a hook.
youtubers dont know what theyre doing lol.
Yes it should.
If you don't prefix your hooks with use, React can't analyse if you've broken rules of hooks such as reordering or changing number of hooks between rerenders and if you do break them would cause unpredictable behavior (BUGS). As long as you don't break rules of hooks you don't technically have to prefix it with use, but it is very bad practice and very much not recommended, and very much a sign of a junior dev trying to build a youtube channel, which is OK I guess.
Few points to improve counter example:
1) As I know there's recomendation to name custom hooks starting from `use`, so better to call function as useCounter, it will be more obvious to other develoeprs.
2) Because hook act like useState, better to call it const {counterValue, increment} = useCounter(). It will be more comfortable for another developer understand that first variable is scalar and second is function.
One thing I'd like to add at 8:36 is that the `increment` function will be always recreated. As far as I understand, re-rendering a component means re-invoking the function that defines the component(e.g. `App`). When `App` is called, `Counter` will be invoked too, therefore the returned `increment` will different than the one from the previous render.
Great content! The separation of UI and the logical functions is identical to the standalone composition function of vuejs (3.0)
Thank you! I have never worked with Vue, but it looks awesome after the september update! Might try it sometime!
VueJS and AngularJS are two-way data binding frameworks. React is a ONE-WAY data binding framework. So this tutorial makes no sense in modern React as of 2022.
Such a good video.
I've been using react for the past 6 months and I've learned so much.
No its time for me to bring it to a new level and your video helps me a lot.
I am happy to hear! I hope you got value from this!
@@PedroTechnologies oh yes definitely.
Im implementing some of these for the rework of my react webshop.
I dont like at lot of things although I'm proud of it since it was my first big project
But evolving means the project needs to evolve too so its time to turn this thing into a professional app that can be seriously used as a showoff on my portfolio 😅
When you separate components with one display and one logical and you do ctrl click in a function from the display component it will
Not jump to the logic, but to the instance, so you won’t be able to travel easily through the code, which is not good maintainable concept in my opinion
you can ctrl click the import and it will get you to the file where the function is defined
My folder structure is getting out of hand so this is very helpful.
I use an index.js file that default exports the jsx file so it cleans up the import statements.
I do this too! I think its good practice!
Making seperate logical component could be seen as making a custom hooks instead coz essentially they are stateful logic. Correct me if I am wrong. Also using 'use' in front of counter filename would give context to the file that it is not returning jsx instead just few variable(as is the idea of hooks).
your tutorials make react easy and understandable..thank you bro👍👍👍👍👍
Glad you like them!
Hi, I wanted to know because I don't see many resources regarding splitting your code like this on RUclips. I tried and the problem that every time I call a function for example imagine we have a Counter function (like in the video) and then another RandomColor function for example. If I call my Counter function it will also call RandomColor and that's not really something you want. Do you have a solution? Thanks a lot.
Great presentation. Coming from Django-Python, the best practices are less obvious, since the structure of the programs does impose in a way the app writing procedures. Compared to PNP, JavaScipt and React there are so many ways to write a program it is at first more difficult to understand... Freedom in a way is a lonely prison : -)
I don't think it matters if the function is created in the dom part of your component or right above it. The whole component is re-evaluated as a whole every time React detects the returned value might change (like when invoking `setCounterVal`)
You mentioned the inline function being recreated every redraw, but isn't the 'increment' function inside your hook recreated every time as well? I mean, the entire component is being called on rerender, which will always call your Counter hook which in turn will always create a new function with a new 'counterVal' closure anyway. Only if you had memoized or useCallback'd the 'increment' function it would be consistent between updates. Or am I overseeing something?
I was looking for this comment and i think you're right. This thing with recreating functions only matters when something like React.memo is used :)
hi pal. i got my first job and its all thank to you :))
thank you so damn much!!🤩
btw, i wanna ask, would you mind to make a vid bout mvc and mvvm? and a reactJs example for each would be good😶
Very Usefull, after few weeks reading and looking for a guide for the best practices, you teach me a lot of stuff. Thanks!
Glad it was helpful! I am happy that I was able to help you!
Hey @PedroTech, I've been refactoring some of my projects with this pattern. One thing I have noticed though is that it becomes increasingly difficult to debug these apps since logic is held in the logical components, which don't appear in the react devtools debugger. Any advice here?
Hey, I believe after v4 devtools have support for hooks. That is how I debug when using this pattern!
Awesome content, I would love to see some practical approaches to problems, for example, how is the best way to display a table, or how is the best way to create Modals, etc. Greetings from Colombia. Keep going!
Hey, thank you! I can make videos on both of them! People have been requesting videos on tables so I will probably make one about that soon!
This helps so much. Thank you! Will starting adding a logic file to each of my components directory.
This channel is awesome. Learnt so much already.
Glad you enjoy it!
Nice video! I've been working on a large project by myself always find myself struggling because I'm not doing the good practices I'm supposed to. Very helpful video!
Yes, make a video on validations!
Awesome! Yeah, for large projects best practices are crucial! Good luck on the project!
I'm still pretty new to React, so forgive me if I am overlooking something obvious here. How would you go about handling props when you split your component into separate logic & layout files? If you pass the props into the component element it would only be available within the layout file but not the logic file. Would you just skip using props altogether and do everything via context? Thanks!
Hey, you can pass the props to the logic component through the paranthesis as an argument to the function. Example: if you wanted the counter state in the Counter logic component to have an initial value of 40, but you wanted it to be passed to the ui component as a prop. Then you can just pass the prop in the paranthesis of the hook call:
const { counter, increment } = useTest(initialVal);
- Then in the logi component make it receive an argument called initialVal. and use it there!
kinda like codeigniter 3 structure + nuxtjs structure. Your tips are great, thanks mate! Btw, is this called MVVM or something like that?
Nice video. Thank you, I've learned( seperate UI and logic in component )
I thought custom hooks need to be prefixed with the word "use"
Its not needed but its recommended. I didn’t show it cause i thought it would be confusing, but now I see it was actually better to already show it with the use prefix
Since this is a video about best practices this is kind of a fail. Hooks may only be called unconditionally at the top level of a component. “Use” prefix is used by eslint to warn developers about wrong usage of hooks. This has been best practice from day one.
never admit I have OCD but this is satisfying
Hahaha Thank you!
Excelente video. Enhorabuena!. Gracias
06:03
"Btw this how you use custom hooks in react"
Had me dead I was was already amazed at the fact that you were doing this I have never considered this and then you hit me with the James Bond i am showing you 2 key things at once, this shit is easy vib!!! lol
Thanks king!
Excellent React Best Practices Tutorial. Thanks, Pedro
{2021-11-17}
Hey what is your vscode theme and extensions you have installed?
There is nothing wrong with what you suggest, but in my opinion separating the logic from the view for a simple component actually makes it harder for additional developers. Why? Most small components only have a few logical functions, typically involving onClick handlers as you show here. So by moving the "logic" into a separate file, and destructuring the components as you've shown, just creates additional boiler plate code, as now instead of seeing the simple onClick handler (and understanding the implementation at a glance) one must wonder, hmmm, what is happening in the Counter implementation. It may seem like a small thing, but I'd rather not have to open a second file to see what could have easily appeared in the first.
By introducing the Counter component, now when you add something to it, like a new function, you must explicitly return it, meaning you'll have to modify the return value of Counter, and add a new destructured variable to App. Again, that's not huge but it's overhead that would not have been needed if you just left the onClick handler in the App component.
To make things potentially better in the future, your solution makes the current situation slightly more complex. To me this seems like premature optimization.
Finally, for anyone who has ever done object oriented programming, it would seem natural for Component to encapsulate logic, data and view. Again, I'm not saying your approach is wrong, but I'm just not convinced it's necessarily better either.
I think a better way to refactor a class would be to move Button out to it's own component, and have it deal with its own concerns. Have a great day!
Your other tips are good though.
how did you get the import line having file size? what vscode extension is that?
Its called import cost!
vídeo muito bem explicado, parabéns
Obrigado mano!
The part about inline lambda isn't right. The function will not be recreated as the browser is smart enough to cache it (in fact functions can't really be created at runtime at all, except for using eval()). The reason why it's bad style to use inline functions is first of all, you can't reuse the function further down and also it bloats up your html code and makes it kind of difficult to parse for humans if they just want to understand the element hierarchy for example. So really, the same rules apply as generally in code - it is fine to do as long as your code remains clear to read and it can improve readability for short snippets. But it's bad to add large functions or put even simple things in when it's already very bloated by other stuff (like tons of attributes or elements or inline CSS for example).
I'm a front end for a while but i'm learning React so i'm new at this and your video helped me a lot! Thanks!
One question though... Why did you create folders with first capital letter? Why "routers" and "Helpers" has this different formats? Is it because you were just rushing and forgot to fix or people really does that? I'm very used to programming and POO so i understand the pattern on the code but these folders with capital letters and not bugs me in React project.
Thank you! Yeah it was a mistake, there is no problem with keeping the names with capital or lowercase, however it should be the same throughout the project! Sorry about the mistake!
@@PedroTechnologies Thank You! I always like the clean way for coding so i'm definitely will use you approach. Thank you for the "response"!
Yes!! Needed this!
Awesome!
that's amazing i like it😍
Awesome video as always!! I just have a question though about writing custom hooks. Is it not best practice to put the word ‘use’ in front of what ever name you are giving the hook? Thanks
sidenote: the standard naming convention of custom hook is prefixing it with 'use'. Example - useCount() instead of Count()
Bruh which theme you use ?
Great video! Isn’t it a disadvantage to do styles for your components individually as you’d lose out on global class styles?
THank you! You can add global styles with styled components!
You'd usually have a mechanism for importing styles from some common ancestor. Generally speaking though, aside from a couple constants such as colors or text sizes, it is very rare to share styles, particularly classes among different components.
validations validations validations 😁😁 you are doing a great job man, thank you so much :3
Hahaha Apperently people are wanting a video on validations so I should make one! Thank you for the kind words!
i want to put my all api call code in one saprate file . and then call in my diffrent componant .make video or provide git code structure
thank you in advance .
Just finished watching, very useful!
Glad you enjoyed it! If you have any questions lmk!
Which theme is that? I love it. I just keep looking at the blue part.
Hey, I believe it is the buloco dark theme or andromeda
Great informational video! You teach this in a very simple way
Thank you! I really appreciate the support!
Hi Pedro i learn react i have the basics but i dont know how to progress more??
You can always improve by building more projects! I plan on making a video on this!
Validations with private route implementations would be great ✌️
I have a video on private routes! Video on validations is coming out soon!
Nice! What is your icon extension on VSCode?
Material Icon theme! Por sinal, ainda não perdoou o fortaleza por ter rebaixado o bahia ano passado kkkkkkkkk
@@PedroTechnologies KKKKKKKKKKKKKK Não precisa perdoar, a gente tá sofrendo as consequencias agora KKKKKKKKKKK
Very nice👍 video, but how did you get import cost to work? My import cost displays nothing when I import or require a package.
I just installed it and it worked hahaha! Try uninstalling it!
@@PedroTechnologies 😂, is yours the wix.importcost one?
Hey @PedroTech, I really appreciate this video and want you to make a video on the Validations folder that you talked about in this video. I will be waiting eagerly, thanks.
thank you so much this is the one which I want, waiting to formik with an advanced concept like formik and Advance Schemaa in Yup, can you do a video on react tool-kit like async createAsuncythunk and createEntryAdaptor
Glad you liked it! I am making a video that goes more in depth on YUP. I have a video in my channel on Formik if you want!
shouldn't it be useCounter?
Can any one tell me what theme he is using?
Nice job from Pedro!!!!!
Thank you!
Bro vs code which theme extension you use in this video.
Hey, I am using the Andromeda theme!
ur videos are awesome dude tons of help
Thank you! I really appreciate it! I am happy I could help!
why don't you call it useCounter ?
♥♥♥
Which theme do you use plz tell me
I think I used Andromeda in this video!
should be called "useCounter" as you're making a custom hook O_O, the "use" prefix is used so React knows it's a hook.
Great!
this video is so good
mm this is so clean
Thank you!
React Best Practices, and you don't update the state functional, when use the previous value? LOL, the correct way to do it setState(prev => prev + 1) of course, and also, custom hooks have to start with the ''use'' keyword.
I agree, I like getting constructive criticism. The 'use' keyword was my bad hahaha I thought that it would be easier to understand for those who were beginners but I agree it makes it more confusing so in my new custom hook video I explain that you usually use the "use" as a prefix to hooks. About the state mutation, this is only better in certain situations which weren't the purpose of the video. I am planning on making a new video talking about best practices in react and maybe I will talk about this as well and give some examples!
Very informative thank you Pedro, keep up the good work
Thank you! I am glad you enjoyed it!
Yes make a video on validations😂
Hahaha ok! Video on validations will come!
@@PedroTechnologies
And yeah dude...I had requested for the best practises video in your discord ...
But I wanted to see more.....like...
You can take your MERN stack application....and then ...like how to separate the API call logic IN a separate folder ... I am very bad at explaining stuff...but I hope you got it what I am asking for 😅
You mean like, separating the api call logic and the ui? This is the standard, I can make a video about this. I should have put an example in this video lmao Sorry I forgot!
@@PedroTechnologies
It's okay
We always have a slot for part 2😉
Yes you are right ...separating the API logic and UI ....
Suppose we load an array from an API and then we store it in a temp array...so that we don't need to recall the API again and again...but then...if we write the API logic separately...how do we manage the data efficiently...that's what I am looking for....I am so sorry ..I explain poorly..but I hope you slightly got an idea
Great Job
Thank you!
hello sir could you make videos on some redux examples please
Pedrinho nao vem nao q sei que vc e braisleiro hahaha :D
I had to stop at the first advice. Why did you name it Counter? It's not a component, it's a custom hook. It should be named useCounter.
Also, you didn't separate presentational/visual and logical component (because you didn't create a separate component at all). To do that, in your case, you could create a component that would take onClick and message in props and display the button and text. Then you pass in increment function to onClick and counter to message. That way the component is not containing business logic (counter, increment) but is a visual, reusable component.
Hey, I am sorry you didnt like the video! As I have answered to some other comments, I am totally aware that normally you put the use as a prefix to a custom hook. The video was made a while ago and I thought it would be better not to focus on common standards in order to not confuse beginners, I see that It wasnt the best idea. However, how did I not separate the ui from the business logic? I understand what you mean, that I could create a button and text component and just pass the onclick function as prop, however this was not the intention. Using a custom hook basically removes all the logic from the UI component and put it all in the hook! I appreciate the feedback!
@@PedroTechnologies Hey, thanks for the answer. It's not that I didn't like it. I just think it has some misconceptions. So, once again - I wouldn't consider hook to be a component. Therefore, I don't consider what you done to be separating visual and logical components. You still have logical component, only with the business logic placed in a custom hook. However, as opposed to the visual/logical component separation, you are not passing it as a prop from logical (often referred as "container") component to visual component. Instead you are importing the hook directly. In other words - the popular pattern of separating presentational and container components is based on a kind of dependency injection. Here you've done something different - you have a reusable hook, but you're importing it directly, in a single, logical component. I hope I explained clearly my viewpoint.
Great content! Keep it going
Thank you! Glad you liked it!
tutorial for redux reducer
I don't use redux as I am a fan of the context API! Sorry bout that!
React the Angular way :)
2nd Viewing {2022-02-14}
Happy to hear :)
good vid
Thank you!
This is bad practice, it immediately goes against the documentation's specific instructions. What he called a "logical component" is a custom hook, and naming it "Counter" is bad practice. Custom hooks are great for sharing logic between components but does nothing but bloat your codebase if you are extracting the logic for one component.