DEV Community

Athul A
Athul A

Posted on

Difference Between Class Based and Function Based Components in React!

Class Based Components were used in react before the release of hooks which supports state changing mechanism etc in function based component.
We also use Class Based Components nowadays but function based component is more reliable with the release of react hooks. Again it depends upon on the user which one to use.They can use both or any one.
In Class Based Components the state is managed only using objects whereas in function based we can have different values

Function Based Component

const [showUsers, setShowUsers] = useState(true);

//To Update this state
//we need to call setShowUsers() function and pass the value
Enter fullscreen mode Exit fullscreen mode

In function based Component the new state will overwrite the previous state,but we can do merging by using our own logic

Class Based Component

 constructor(){
    super();
    this.state = {
      showUsers:true,
    };

  }

//To update this State
this.setState((prevState)=>{
        return {//Things to be returned}
    })

Enter fullscreen mode Exit fullscreen mode

The New State will get merged with the previous state it won't get overwritten as in function based component.

Class based component cannot use React Hooks!!

Thanks for reading :)
I use function based component!!What about you?

Top comments (0)