Class-based Components vs Functional Components

Before knowing the differences let me tell about components first so that it will lay the foundation for better understanding,

A component at the browser level anything on the user interface which is mounted on the screen and at the code level in a functional component is something that returns a JSX element or returns null or in the case of Class-based components, a class which extends the React.Component super class and also has a render method that also returns a JSX element or returns.


So, the basic concept in any component is that when the state is changed by calling the setState function or through useState hook the component re-renders, but the major difference is the mutability of components – A class-based component would be mutated but a functional component is not mutated.


This means whatever the object that has been created for the class component that internally stores the initial value of the state is mutating or changing that variable(state) directly. So, the previous value of that particular variable is lost forever unless we have some kind of extra backup function to store the value the variable beforehand.


But in the case of functional component, they are called again with updated state values that means when the component is mounted on the screen and when the state is updated through the useState Hook’s function, it tells React to update the functional component to replace the useState with the new variable so what happens is when the component function is called again useState(x) is replaced with useState(y), So therefore technically we are not mutating the state variable instead React is just re initializing the variable with a new value when the function is called and hence re-renders accordingly.


re-render flow chart

That's it! that's the major difference between a class-based component and functional component!