DEV Community

Cover image for React components -(Class component v/s function component)
Manikandan K
Manikandan K

Posted on

React components -(Class component v/s function component)

What is a Component?

  • Component is independent and reusable bits of code.
  • Components let you break up the user interface into separate pieces / that can then be reused / and handled independently.

Image description

Class Component v/s Function Component

Class Component :

  • To define a React component / as a class, extend the built-in Component class / and define a render method.
class Welcome extends React.Component {
    render() {
        return <h1>Hello, {this.props.name}</h1>;
    }
}
Enter fullscreen mode Exit fullscreen mode
  • To use Lifecycle methods in class Components.
  • Little complex compared with Functional Components.

Class component without state

Image description

Class component with state

Image description

Function Component :

  • React functional component is a simple JavaScript function / that accepts props and returns a React element.
  • These functions may or may not receive data as parameters.
// Normal function 
function Welcome () {
        return <h1>Hello, {this.props.name}</h1>;
    }


//Arrow function
 const Welcome  = () =>  {
        return <h1>Hello, {this.props.name}</h1>;
    }

Enter fullscreen mode Exit fullscreen mode
  • Function components are called stateless components (Before Introducing hook).
  • Access state and other react features (lifecycle methods) using hooks.
  • Easy to create Function components.

function component without state

Image description

function component with state

Image description

Top comments (0)