There are two types of components in React: functional components and class-based components. Class-based components are the more traditional type, but with the addition of Hooks in React 16.8, functional components are easier and faster to create. Let’s look at the major differences between functional and class-based components when it comes to creation and rendering, props, and state.
Creation & Rendering
Functional Components
To create and render a functional component, define a function that returns a JSX expression. That’s it!
const Greeting = () => {
return (
<h1>Hello World!</h1>
);
};
Class-based Components
To create a class-based component, you need to define an ES6 class that inherits from the React.Component
base class. Your component should have a render()
function that returns the JSX markup.
import React from 'react'; // Don't forget!
class Greeting extends React.Component {
render (
return (
<h1>Hello World!</h1>
);
)
}
Props
Functional Components
Props in functional components are nothing but parameters to the function, contained in an object. You may either accept the entire props object, or destructure specific props. Both methods are shown below.
const ProductDisplay = (props) => {
return (
<h2>{ props.product }</h2>
);
};
const ProductDisplay2 = ({ product }) => {
return (
<h2>{ product }</h2>
);
};
Class-based Components
Props in class-based components work a little differently: they are sent to the superclass’s constructor, and accessed through a props
object on the class.
import React from 'react';
class ProductDisplay extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<h2>{ this.props.product }</h2>
);
}
}
State
Functional Components
With the introduction of Hooks in React 16, managing state in functional components became so much easier. To create a state, we only need to use the useState
Hook, which will return the state variable and a setter function for that variable.
import { useState } from 'react';
const Count = () => {
const [count, setCount] = useState(0); // Set initial state to 0
return (
<button onClick={() => setCount(prev => prev + 1)}>{ count }</button>
)
};
Class-based Components
State in class-based components is created and managed via a state
object on the class. This object is intialized in the constructor and can be accessed from anywhere inside the component. To mutate the state, you have to use the setState
function.
import React from 'react';
class Count extends React.Component {
constructor() {
this.state = {
count: 0
};
}
handleClick () {
this.setState(prev => {
return { count: state.count + 1 };
});
}
render (
return (
<button> onClick={ handleClick }>{ this.state.count }</button>
);
)
}