Trying to Choose Between Functional Component and Class Component in React

introduction
There are a lot of speculations as to what type of component to choose while coding with react. React is an open source JavaScript library (remember it’s not a framework, but a library) for creating interactive user interfaces, which was created by Facebook. React created a way for individuals to build single page applications (SPA) as it solved the draw backs, we had with single page apps. Before the advent of react, single page applications manipulate the DOM really slowly and you have to work extra hard to make sure your data works in hand with your user interface. But react helps us manage our UI and also provides us a virtual DOM which is way faster than manipulating the real DOM.

These two types of components have been existing since the onset of react in 2013. As at these periods functional components were used for less complex apps while class component were used to build more complex apps as it supports states, tracks lifecycles and other features, which you can still use till date. Over the years a new feature was added to functional component called Hooks which let us use state and other react features in the functional component. For more understanding of hooks click here. States are objects that hold data or information about a component in react, these data or information may change overtime. Introduction of hooks have greatly improved the way we use react. So let’s dive into each of these components and see their different features and syntax.

Class Component

class Example extends Reacts.Component {
render(){
return <h1>This is a class component</h1>}
}

I guess we all know that Pascal Case is the accepted way of naming a component in reactExample.

States in Class Component

Like we defined states earlier, states holds information or data about a component in react which may change over time. in class component we can update the state, when a user interacts with it or maybe a server response using the setState() method and the initial state is been assigned in the Constructor( )method using the the this.state object. different data type can be passed in the this.state object, which can be string, boolean, numbers, etc. A simple example showing how we use the setState() and constructor()

class Example extends Component {
  constructor() {
    super();
    this.state = {
      example: "This is a class component",
    };
  }
  changeText() {
    this.setState({
      example: "implementing the setState() in class component",
    });
  }
  render() {
    return (
      <>
        <h1>{this.state.example}</h1>
        <button
          onClick={() => {
            this.changeText();
          }}>
          Click!!
        </button>
      </>
    );
  }
}

If you're using visual studio code as your code editor it is very important for you to install prettier as it helps format your code and makes it looks readable and more professional

In Example component above, what the example basically do is to update the state within the constructor () method where the this.state object is assigned to theexample: "This is a class component",: a key and its value. which is rendered as a <h1> tag within curly braces { }, the curly braces is an essential syntax when writing javascript in JSX . The button tag beneath the <h1> tag click ! , when clicked will change the text in the <h1> tag to the updated text that was set inside the event handler onclick{ }. The function changeText() contains the this.setState() which updates the state { example: "implementing the setState() in class component", }

notice the constant use of the 'this ' keyword, note that when writing a class component "this" keyword is necessary, for better understanding of the this keyword click me!!

Props in Class Component

Props are referred to as "properties". props are passed into react component just like arguments are passed into functions . Props are being specified as attribute just like your html. for example if the name attribute is "name " we assign a value to name. so basically, props are object that contains an attribute and its corresponding value. Data can be passed from parent component to the children component, but this data is immutable, which means that we cannot modify the props across another component. here is an example

class Introduction extends React.Component {
  render() {
    return <h1> Hello, my name is {this.props.name} </h1>;
  }
}

class App extends React.Component {
  render() {
    return (
      <div className="App">
        <Introduction name=" Queen Elizabeth" />
        <Introduction name=" Margret  Edeh" />
      </div>
    );
  }
}

The above code snippet explains props, in the App root component, the introduction components was rendered twice, this explain reusability of components in react but have different value for the name attribute, wonderful isn't it ?. the this.props is a necessary when writing props in react, it is absolutely required. Instead of writing "Queen Elizabeth" in your component Every time you need it anywhere in your code you could simply give the component an attribute and set it to " Queen Elizabeth" then insert this.prop.name within curly braces where it is required. Remember i said that "props are immutable" so if we try to give the prop another value like in this example;

class Introduction extends React.Component {
  render() {
    this.props.name = "Rihanna"; //ucaught TypeError: Cannot assign to read only property 'name' of object
    console.log(this.props.name); //ucaught TypeError: Cannot assign to read only property 'name' of object
    return <h1> Hello, my name is {this.props.name} </h1>;
  }
}

assigning a new value to the props throws an error message in the console and does not renders anything on the screen

Destructuring Props

Destructuring props is just like destructuring an object. Destructuring props gives us the ability to eliminate the use of the this.props keyword anytime we want to use the props. Example

class Introduction extends React.Component {
  render() {
    const { name } = this.props; //destructuring a props
    return (
      <div>
        <h1> Hello, my name is {name} </h1>;
        {/* no longer a need for the this.props keyword*/}
        <h1>Nice to meet you {name} </h1>
      </div
    );
  }
}

Destructuring props makes our code more simplified.

Functional Component

Functional component has been improved over the years with some added features like Hooks Here is a syntax for functional component


function App(){
   return <div className="App">
     <h1>Hello, I'm a Nigerian</h1>
    </div>
}

Using Sates in Functional Components

Initially, we could not use state in functional components because it was only supported in class components. over the years hooks were implemented in functional component. The hooks that enable us to use state in functional component is called useState The useState( ) hook returns an array of the current state and a function ( setState) that we can use to update the value of the current state. The array is being destructured so we can can see the variables the array holds that is, the initial state and the updated state lets see an example

import React, {useState} from "react"
function App(){
  const [country, setCountry] = useState("i'm a Nigerian")
   return <div className="App">
     <h1>Hello, {country} </h1>
    </div>
}

in other to use the useState hook we need to import it from react , just as it is in the example above. the array [ country , setCountry] the first variable could be any word of your choice, it holds the current state, while the second element in the array should always have the prefix 'set' then the first variable. this is the normal and acceptable naming convention in the use state hook. The code snippet above is rendered on the screen as 'Hello, i'm a Nigerian'. since it's a state and not a props we can update it.


function App() {
  const [country, setCountry] = useState("i'm a Nigerian");
  const change = () => {
    setCountry("i am a Canadian");
  };
  return (
    <div className="App">
      <h1>Hello, {country} </h1>
      <button onClick={change}>Change</button>
    </div>
  );
}

The setCountry( ) method was use to update the state. A value was passed to the SetState method in the event Handler. when the buttton is clicked the text renderd on the screen changes to ' Hello, i am a Canadian'

Props in Functional Components

Props in functional components are similar to that of the class components, the difference is the absence of the 'this' keyword. We also destructure in a similar way without the 'this' keyword. they are also immutable in the functional component

function Food(props) {
  return <h1>I love {props.fav}</h1>;
}

function App() {
  return (
    <div className="App">
      <Food fav="Beans" />
      <Food fav="Yam and Egg sauce"/>
    </div>
  );
}

As you can see in the example above there wasn't a need for the 'this' keyword.


function Food(props) {
  const { fav } = props;
  return <h1>I love {fav}</h1>;
}

function App() {
  return (
    <div className="App">
      <Food fav="Beans" />
      <Food fav="Yam and Egg sauce" />
    </div>
  );
}

Destructuring props is also similar to that of class components

Differences between Functional and Class Component

The functional components doesn't require the render method Class component require the render() method that returns JSX.

To use states in functional component we use the useState hook.
To use State in class components we use the constructor method and the setState function.

Functional components use the useEffect hook instead of lifecycle method useEffect
Class components uses Lifecycle method componentWillUnmount etc. Lifecycle methods

Conclusion

I guess everybody has their preferences as to what type of component to use. Functional component gives us more flexibility in react, we have a lot of complex functionality without writing a lot of complicated codes. We can't outrightly say that this particular component is the best one to use. But I advise that as technology and everything is advancing, we should also follow the trend so as not to be left in the dark.