

Yet I prefer using functional components over class components for those reasons listed above. The team is seeking to gradually adopt functional components with hooks in newer cases, which means that there is no need to switch over the existing projects that utilize class components to the entire rewrite with functional components so that they can remain consistent.Īgain, there are a lot of valid coding styles in React. And as promising as it sounds, new hooks are recently introduced for functional components such as useState or useEffect while also promising that they are not going to obsolete class components. To follow up, the React team mentioned in earlier days that they will make performance optimizations in functional components by avoiding unnecessary checks and memory allocations. It should also be noted that the React team is supporting more React hooks for functional components that replace or even improve upon class components. Using functional components can easily avoid this kind of mess and keep everything clean. Class components can also be confusing with so many uses of this. There are pros and cons in both styles but I would like to conclude that functional components are taking over modern React in the foreseeable future.Īs we noticed in the examples, a functional component is written shorter and simpler, which makes it easier to develop, understand, and test. See life cycle with class component in Codepen Conclusion

See lifecycle with functional component in Codepen Remember, the setState function takes argument(s) of state, props(optional) if needed. Setter is pretty much the same, just different syntax.Īlternatively, you can write an onClick function. And inside JSX, we use to access the value of the state key we defined in the constructor to display the count. Inside the constructor, you will make a state object with a state key and initial value. Otherwise, this.props will be undefined in the constructor, which can lead to bugs.”īasically, without implementing the constructor and calling super(props), all the state variables that you are trying to use will be undefined. When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. “ The constructor for a React component is called before it is mounted. Here is the definition from the official documentation: Firstly, we need to understand the importance of the React.Component constructor. The idea is still the same but a class component handles state a bit differently.
