Introduction to React
Class vs. Function components
It is important for you to understand that there are two different ways of creating components in React: class components and functional components. In older versions of React (before version 16.6 was released in February 2019), class components supported more features compared to functional components and made class components the standard in React. With the React update, functional components were updated to support more features, such as handling state (more about state in this section).The update enables a more concise way of programming React. In addition, the syntax for writing functional components is less cumbersome compared to class components. It is important to understand the differences between class and functional components when learning React, as you will be exposed to the two different syntaxes for what is essentially the same thing. We recommend using functional components because it’s less verbose and you don’t need as much knowledge about Javascript classes. However, older tutorials and results on Google sometimes still use class components. That’s why you have to know about both ways of writing components. Below an example of a functional component that returns a header element:
Code example: functional component Welcome
function Welcome () {return <h1>Hello world</h1>;}
The same component can also be written with help of the arrow function syntax and would give the same output:
const Welcome () => {return <h1>Hello world<h1>;}
Code example: Corresponding class component Welcome
class Welcome extends React.Component {render() {return <h1>Hello world</h1>;}}
Watch the video below for an explanation of the differences between functional and class components: