This post was originally posted here
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.
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
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