Functional components are taking over the React world and I can see why

Updated: Sep 20


React components

When building out the frontend of your project with React, you’ll be needing to use React states, otherwise, you wouldn’t be using React. I’ve been working on an ongoing project for the past few weeks now and after using class components initially, I can really appreciate the advantage of functional components.



Introduction of usestate


The release of React 16.8 brought with it the Hook “useState” which, as the name suggests, allowed functional components to use React states. Beforehand, to introduce state you’d use a class component, nowadays there is a choice.


Advantages


Handling state with a class component requires implementing a constructor and calling super(props) to define objects with keys and initial values. With functional components, the hook takes the initial value as an argument and can be destructured into the current state and a function to update it. This is all done on a single line whereas the class component calls for nesting and a minimum of 5 lines as shown below. On top of this, the class component needs a render method, taking up another 2 lines.


Functional



Class



With the state defined, you then want to access it inside your JSX. With functional components, the states can be used as simple objects. With class components you must call this.state.keyName to access the corresponding value of the state; once again a much bulkier implementation. I’ve also found that you end up using “this” all over your document and it ends up very cluttered.


Going forward


Due to the much clunkier nature of states in-class components, I will certainly be opting for the much more concise functional component. This makes for quicker, more efficient and cleaner looking code that’s easier to read and understand. Class components aren’t going to be phased out any time soon but going forward updates will be much more focused on functional components.


Elliot Martin is a full-stack software developer with one of our partner companies working on some ongoing software development projects. Elliot is a games master and facilitate most of the team bonding sessions at WayMaker Digital.

2 views0 comments

Recent Posts

See All