Class Components and Functional Components.

A quick rundown for reference.

Photo by Isaac Smith on Unsplash

Welcome! In this post I will be going over a basic comparison between class components and functional components in react. While working on a project recently, I googled a lot of react component related questions and I noticed that the code examples I ran across we’re either written in the context of a functional component or a class component, and as we get further along this post hopefully you can start to see their differences and why you can’t apply certain solutions to your issue if they were written for a functional component and your code is written in a class component and vise versa. So before we get into the nitty gritty, let’s start this off by having a clear understanding of what react components are. According to the react documentation —

Components let you split the UI into independent, reusable pieces, and think about each piece in isolation…Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.

Class Component

Let’s breakdown what a Class Component is, for starters it is a JavaScript class, right? A blueprint for creating objects that extends Component from React and returns JSX using the render method. Component from React, gives our class the ability to access functions like componentDidMount, componentDidUpdate, componentWillUnmount and render. Let’s go over these, shall we.

The componentDidMount() method allows us to execute the React code when the component is already placed in the DOM (Document Object Model). This method is called during the Mounting phase of the React Life-cycle i.e after the component is rendered.

The componentDidUpdate() method is a part of a React components lifecycle. It is called when a component got updated. This might happen if new props have been provided by a parent component or an internal state has been changed.

The componentWillUnmount() method allows us to execute the React code when the component gets destroyed or unmounted from the DOM (Document Object Model). This method is called during the Unmounting phase of the React Life-cycle i.e before the component gets unmounted.

The render() method is the only required method in a class component, and is responsible for describing the view to be rendered to the browser window.

So we know what makes up a Class Component and now lets see what one looks like in our code.

Let’s take a moment and define lifecycle methods before we move forward.

Lifecycle methods —

Each component has several “lifecycle methods” that you can override to run code at particular times in the process.

Functional Component

Let’s break down what a Functional Component is just like we did for the Class Component. For starters it is a plain JavaScript function that takes in props as an argument and returns JSX. There is no render method in functional components it will simply return the JSX value. And to access a functional components lifecycle, we would use react hooks (more on that later). Before we continue let’s take another second, to define props and JSX.

React Props

It is an object which stores the value of attributes of a tag and work similar to the HTML attributes. It gives a way to pass data from one component to other components. It is similar to function arguments. Props are passed to the component in the same way as arguments passed in a function.

JSX

JSX is an inline markup that looks like HTML and gets transformed to JavaScript. A JSX expression starts with an HTML-like open tag, and ends with the corresponding closing tag.

Alrighty, now let’s take a look at a Functional Component in the flesh!

Differences

Let’s get into some of the major differences between these two ways of using react components. First up, the this keyword —

For starters, the this keyword is used mostly in Class Components, in comparison to Functional Components. In fact, Functional Components do not require the use of the this keyword when referencing a method or attribute. This is because arrow functions automatically bind this to the surrounding code’s context. Class Component methods on the other need to be told what context they’re being called in, which is why we use the this keyword.

Next up, Local State

In a Class Component, we set up local state in our class by passing props to the base constructor using super(props) and then setting an initial state in our class constructor, which has to be an object. We are then able to manipulate the state, using this.setState(). setState() will trigger a re-render any time the state is updated. In Functional Components, we can gain access to the usage of local state with the {useState} hook from React. useState takes in one argument and that is the initial state. Also the return value for useState is the current state value and a corresponding function to update the state. Now, whichever you choose to use keep in mind that both setState and useState will not update the state immediately, why? the not so simple but simple answer is that they are queues. More on that over there….

Up next Lifecycle methods and Hooks —

Above we briefly took a look at Lifecycle methods and I also mentioned, that they are not available in functional components. However, with functional components we do have access to hooks (which are not available in classes by the way, just to be clear) and with one hook in particular we can replicate the functionality of three Lifecycle methods alone. Introducing the useEffect hook, this bad boy allows us to implement ComponentDidMount, ComponentWillUnmount, and ComponentDidUpdate in functional components. Instead of using the componentDidMount method, use the useEffect hook with an empty dependency array. Instead of using the componentWillUnmount method to do cleanup before a component is removed from the React tree, return a function from the useEffect hook with an empty dependency array. And if you pass nothing as the second argument to useEffect, it will trigger whenever a component is updated. Again lets, slow down and define.

useEffect —
In the simplest terms, useEffect is a hook that allows you to perform side effects in functional components. For even more detail, these effects are only executed after the component has rendered, therefore not blocking the render itself.

Dependency Array —

The dependency array is the second optional argument in the useEffect function. As the name implies, it is an array of dependencies that, when changed from the previous render, will recall the effect function defined in the first argument.

In conclusion, both Functional and Class Components have their advantages and disadvantages. According to the React documentation, there is no plan to discontinue classes in React so choosing between the two really comes down to the developer and what works best for their applications. Functional Components seem to be taking over right now and converting “old” code into “new” code seems to be pretty common too, but I also found it quite interesting that not all Class Components can be converted to Functional Components or the hassle to do so might not be worth it. Some cases could include; the need for a constructor, if you need to extend a component, if you need to implement some complex pattern where you’re updating a couple of state variables at once, and need to run a specific side effect, and i’m sure there could be more cases.

We have reached the end, thanks for reading. Happy Coding!

References

https://blog.logrocket.com/react-hooks-cheat-sheet-unlock-solutions-to-common-problems-af4caf699e70/

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store