This post was originally posted here
I first started "playing" around in React in 2017, when I got my first job as a developer working for a military base in Georgia. I fell in love with the framework almost immediately as I started to get frustrated with it. You see, by this time, I was still in college getting my degree, I had roughly 3 semesters left, and what we were learning in school was no where near what I was working on in the "real world". Overall, my frustration with React when I first got into was that I was simultaneously learning 3 new (to me) languages in school while learning React for work. And at the time, I did not have a firm grasp of the updated JavaScript platform React was built on.
But, I carried on, and now, 3 years later, I am still no expert on the matter of React, but I feel like I have a much better understanding of the framework now than I did a few years ago. Hell, this app that you are reading this blog on is fully written in ReactJS. I wanted to take some time to organize my thoughts and set up a series on what NOT to do in React, so that I can be a better developer in this realm. And hopefully you, the reader, can find this article helpful in your journey to better understand React.
General Definition
Before we get too far into the idea of Anti Patterns, let us define what I mean by such:
Anti-patterns are certain patterns in software development that are considered bad programming practices.
Keeping Initial State Clean of Props
From docs:
Using props to generate state in getInitialState often leads to duplication of “source of truth”, i.e. where the real data is. This is because getInitialState is only invoked when the component is first created.The danger is that if the props on the component are changed without the component being ‘refreshed’, the new prop value will never be displayed because the constructor function (or getInitialState) will never update the current state of the component. The initialization of state from props only runs when the component is first created.
Have setState() in componentWillMount()
Avoid async initialization in componentWillMount() componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state in this method will not trigger a re-render. Avoid introducing any side-effects or subscriptions in this method. Make async calls for component initialization in componentDidMount instead of componentWillMount
Top comments (0)