Sept 20, 2019

An introduction to React: Difference between Class Component and Functional Component


What is a Component?

First of all, before we go deep in this topic, we should know perfectly what a component really is.

A Component (in React) would be describe as an block or portion of our app which could be reuse in the entire project (and others, maybe), it is usually related with a UI element and its behavior.

Now, assuming you know the basic, let’s check about the two types of component that we can create in a React project, Class Components and Functional Components.

Class Component

This is also called Basic Component. Since ECMAScript 2015, We have “class” in javascript. React uses this syntax to create a stateful component with lifecycle. The state is commonly used to change the behavior of our component or its children.

// App.js
import React from 'react'
import Lamp from 'Lamp'

class App extends React.Component {
  render() {
    return (
      <Lamp />
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('react-example')
);
// Lamp.js
import React from 'react'

export default class Lamp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      isTurnedOn : false
    }
  }

  switchLight = () => {
    this.setState({
      isTurnedOn : !this.state.isTurnedOn
    })
  }

  render() {
    return (
      <div>
        <p>The lamp is <b>{this.state.isTurnedOn ? 'on' : 'off'}</b></p>
        <button onClick={this.switchLight}>switch</button>
      </div>
    )
  }
}

Let’s crack this code. Here we have a “JS class” which inherit functionality from React.Component, next we declare its constructor who received the props as argument. Next, we call super, to pass the data to the parent class Component, this is required when we create this type of component.

The “props” is an object which got all the attributes when we use the component as a tag.

The Lamp component has basic porpose, it render a HTML block with a text and a button.

Clicking the button switch it turn on or off the lamp, here is where our state get into the game, in the line 4, we initialize the state of the Lamp, and after that, we declare the method switchLight, which it will turn the state of our lamp.

this “state” is an object with some properties which will change in the time of the class execution. It shouldn’t be changed directly but using the setState method.

You can change the state in this way to:

this.setState((state) => {
    return { isTurnedOn: !state.isTurnedOn }
})

Functional Component

Now, if we want build some minimal, simple and stateless component, this will help you to reduce de amount of code used and apply the DRY principle easier. The funcional component is a javascript function that return one or some Jxs elements.

Let’s check this example of a Bulb Component.

import React from 'react'

export default function Bulb({ lampState }) {
  return lampState ?
    (<span>
      <img src={'https://cdn2.iconfinder.com/data/icons/flat-icons-19/512/Light_bulb.png'} width={50} />
    </span>) :
    (<span>
      <img src={'https://img.icons8.com/ios/1600/light-on.png'} width={50} />
    </span>)
}

Right here, we have a regular function, it receive an destructured object with a property named lampState, it is turn to a local variable, and we evaluate if is true or false to return a different img tag.

Now, we can use it in the Lamp component to show how their can work fine together.

// Lamp.js
import React from 'react'
import Bulb from 'Bulb'

export default class Lamp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      isTurnedOn : false
    }
  }

  switchLight = () => {
    this.setState({
      isTurnedOn : !this.state.isTurnedOn
    })
  }

  render() {
    return (
      <div>
        <Bulb lampState={this.state.isTurnedOn} />
        <p>The lamp is <b>{this.state.isTurnedOn ? 'on' : 'off'}</b></p>
        <button onClick={this.switchLight}>switch</button>
      </div>
    )
  }
}

That’s it, when we click the switch button, the image of the turned on bulb change.

What about Hooks?

Hooks are the latest feature that lets you use state in functional component. This need to be explained with more details, because we need to dig deeper in some new React concepts , i think it deserve its own article.

Thank’s for reading, if you liked or not, give me you feedback.-

An introduction to React: Difference between Class Component and Functional Component
Commentarios