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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With