Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class based component vs Functional components what is the difference ( Reactjs ) [duplicate]

I am new to React and I want to have a clear idea of which one to use, when it comes to components I get to see there are two types.

Functional Component :

import React from 'react'

const userInput = (props) => {
    return(
        <div>
            <input type='text' onChange={props.nameChanged} value={props.username}></input>
        </div>
    )
};

export default userInput;

Class based component:

import React, { Component } from 'react';
import './App.css';
import UserOutput from './UserOutput/UserOutput';
import UserInput from './UserInput/UserInput';

class App extends Component {

  render() {
    return (
      <div className="App">
        <h3>Assignment Output :</h3>
        <ul>
          <li>
            <UserOutput 
            username={this.state.Usernames[0].username}>
            Welcome to React!
            </UserOutput>
            <UserInput 
            nameChanged={this.nameChangedHandler}>
            </UserInput>
          </li>
                      </ul>
      </div>
    );
  }
}

export default App;

I get to read that we should always try to use a Functional component because it helps in some things and also heard that we should avoid using a Class based component as much as possible.

I am confused which is right and which is not.

Why should try to use Functional component where ever its possible, what are the benefits ?

When should we go for a Functional component and when not, is not clear.

like image 718
Praveen Rao Chavan.G Avatar asked Jun 27 '18 05:06

Praveen Rao Chavan.G


1 Answers

Class Components

  • Class-based Components uses ES6 class syntax. It can make use of the lifecycle methods.

  • As you can see in the example that u have given above Class components extend from React.Component.

  • In here you have to use this keyword to access the props and functions that you declare inside the class components.

Functional Components

  • Functional Components are simpler comparing to class-based functions.

  • Functional Components mainly focuses on the UI of the application, not on the behavior.

  • To be more precise these are basically render function in the class component.

  • Functional Components can't have state (without hooks) and they can't make use of lifecycle methods.

like image 166
Thivagar Avatar answered Nov 03 '22 01:11

Thivagar