React Worst Practices — The Beginning
Hello World 🌎
Just like a carpenter keeps a pencil in his ear, and take it out everytime it is required with lightning fast speed, Similarly I believe these practices should be kept in mind every time and whenever we write React App we should take care off these which in turn will make our performance good and will provide a buttery smooth experience to end users and make application code maintainable.
1. Using Logic Inside Render
This was frequently followed in class based components, with the increasing popularity of funcitonal components we minimised using class components,
but kept doing the mistake.
2. Polluting Render method using anonymous functions
Never user anonymous function insider render/return. It decreases readability, increases complexity of code and sometimes impact performance.
3. Using && to conditionally Render Component
Consider below code snippet:
What will be rendered ?
.
.
.
In the UI 0 will be rendered.
Because even though 0 is a falsy value but it is also a number. And Number is renderable by React.
Hence to overcome this either use !! to convert 0 to bool or prefer to use ternary operator.
4. Nesting Ternary in Render
Nesting ternary is never encouraged. But still in some cases we tend to nest it which is highly discouraged.
5. Not Sorting Props
As our application grows number of props, number of arguments in functions also grows. And if we don’ care to manage them then we can have a messy situation soon. It is advised to keep props sorted. It will increase readability and reduce our time when we are debugging for a bug.
6. Not destructuing props and state
In most of the cases to save some time we directly access props values inside our code. And with time when code increases it becomes hard to find all the usage of props. The prefered way is that we should always desturcture any props, state, object and array before using it.
7. Not using useCallback, useMemo hooks and React.memo
This article is not good place to describe about the awesomeness of these functions. By using these hooks and functions we can limit extra re-renders.
I’ve a separate video demonstrating the usage of these.
https://www.youtube.com/watch?v=o1wig429bHE&t=219s&ab_channel=RahulMishra
However, in this article I will be showing the impact of React.memo().
Consider bellow GIF. I’ve two very simple components.
I am not passing any props to Watch component, but even then when count is changing Watch Component is rendering unnecessariliy.
We can prevent this extra re-render using React.memo(). See the below GIF. Now I am using React.memo in Watch Component and when count changes, Watch Component is not rendering un-necessarily.
Now the Watch Component will only be rendered once.
I’ll recommend everyone to explore about these methods in detail.
Consider Reading Second part of this article:
8. Not Cleaning event listeners and timers
Not removing timers and event listeners from our component causes 2 things:
1. Memory leaks
2. Un Predictable state of application ( multiple instance of same timer and events may got registered)
9. Passing props one by one
Some times we may encounter a situration where we have to simply pass over the props b/w components. And instead of leveraging destructuring we pass props one by one.
Thanks to Mateusz for this suggestion:
Please be careful with this point. If you are not using typescript or propTypes, it can be very hard sometimes to determine what exactly is inside “restProps”. It makes code harder to debug
10. Using Index as a key
React uses key to identify list items. Index as key is only applicable when:
1. Your list is fully static.
2. No Re-ordering and Deletion/Addtion is there.
If you have any of these operations then prefer to use a static unique value for key.
The reason is, Suppose you have a list of 100 item. And you have delete functionality.
Now you have used index as key. When you delete first item, every list item will be re-rendered. Because index for every list item will change.
See the below GIF when I’ve demonstrated both behaviour. Pay attention when I delete the first row of both List.
Blue Border indicates re-render.
12. Avoiding React Dev Tools
If you haven’t used the React Dev Tools then I’ll recommend you to start using it. It has many benefits like in the above demonstration I was able to pull it off only by using React Dev Tools.
- By turning this option, you can check updates to the UI visually and prevent un-necessary render if needed before time.
2. By using RDT you can check
1. what props has been passed to a component,
2. what state is being used,
3. which component is reponsible for rendering specific component
4. And many more….
Here is the demonstration of React-Dev-Tools
13. Using inline CSS
Never use Inline CSS in React.
1. It has performance issue. Thanks to JavaScript Mutability. Read more about Immutability Here.
2. It affects the Readability of code and make things complex.
There are numerours way of Adding styles to our component other than inline CSS.
1. Using separate SCSS/CSS file
2. Using Styled Components
3. CSS in JS
14. रायता फैलाना
Read more about रायता फैलाना
Remember our school days, when we were tought to write application to principal for leave. Do you remember the rules of writting a leave application?
- Date at right side
- Start with a Greeting
- Name and Position
- Subject
- Application Body
- Your Name
Similarly, how we write code has some rules (unsaid/said). How and where we write your code also impact in performance at some extent. Even if we discard the performance impact following rules is always better.
Consider following code:
Lets jot down issues with above code:
- No Import order is followed.
- Creating variables anywhere we wanted.
- Initializing hooks at random places
- Writing useEffect hools in b.w. code.
As application grow, it will become very hard to manage and maintain such code. We should always follow some rules while writing code and this is not limited to React.
Import Order:
- Third Party Libraries
- Custom Components
- Utils Imports
- Constant imports
- Image Imports
- Create file specific Constants
(Separate each import category by one empty line)
Rules for Components:
- Very first line — Destrucutre Props (If there)
- Destructure redux state — (If there)
- Initialize State Variables — (If there)
- Create Refs — (If there)
- Initialize hooks ( useDispatch)
- Write all useEffects
- Create const/var/let specific to Component
- Call functions — If there
(Separate each section by one empty line)
If we enforce these rules, debugging will be super easy. It will also impact the Readability and onboarding new developers will be piece of cake.
With Above rules, the above code snippet will look something like this:
15. divs everywhere
With rise of libraries like React/Vue/Angular we tend to create smaller components for our webpage. Which eases the re-usability, decreases the copuling, increases maintainability of code.
Sometimes we forget about Semantics and keep using divs for everything.
Whether is a sidebar, content , footer, nav bar , we wrap up everything inside div. Which is not good for SEO atleast.
We should follow semantics in our application. And we should use tags like nav, footer, section, article so that when any search engine crawls our page it knows about what content it is crawling.
16. div as Button
If you are making any div clickable, do not forget to add role="button"
in that div. Because <button>
tag has its own benefits like:
1. we can navigate using tab
2. focusable and clickable
If we add click
to div, we are missing these behaviours.
The use of role
is not limited to div. any HTML element in which you add click
should have a proper role
.
I hope this article has added some value to your coding skills.
Happy Coding !!!
Here is the Second Part of this Article: