React JS best practices while building Enterprises applications
I have been developing enterprise applications in react js for the last 4 years and found a list of best practices after making many mistakes while coding. I’m listing the practices and will also explain my mistakes and how I solved them.
- Try not to mix class-based components and functional components in the same
My mistake: In my initial projects I used to mix class-based components with function-based components and It was making my life complex as the syntactical difference was making me confused and I was always getting errors that were really time-consuming.
Solution: It took me around 3 days to convert all the class-based components to functional ones but eased my life.
- Use states only if you’re sure of re-rendering the DOM elements
My mistake: In my first ever project I was using states for almost all the variables to make my life simple but it slowly became sweet poison for my project. When requirements went complex it started re-rendering data. Sometimes it used to re-render the DOM late or early which was really a tedious task to overcome.
Solution: From the next project I started avoiding state declaration until and unless it is mandatory to use.
- Try not to write unnecessary useEffect (side effects)
My mistake: In a very complex project of mine there was a requirement for a lot of re-renders on some minor changes which lead me to a lot of useEffect declarations. Which further made my code very lengthy.
Solution: I started using dependency array in a meaningful way to make my code DRY.
- If possible use fragments (<> </>) instead of div (<div></div>)
My mistake: Initially I was not much aware of fragments so was using div in all my use cases which was increasing the DOM tree size.
Solution: I started using fragments more frequently than div and it improvised my code readability and DOM tree size in browsers as well.