React Function Components vs Class Components

Photo by Ferenc Almasi on Unsplash

What are React Components?

Components are the building blocks of a react app. They are kind of like JavaScript functions. They accept inputs (props) and return React elements. They come in two different types- class components (or stateful components) and function components (or presentational components). The best practice is to use function components as much as possible.

Class Components

A class component is a JavaScript class that extends react Component. They are stateful, contain logic and require a render() method.

To define a React component class, you need to extendComponent, this creates inheritance to React’s Component and gives us access React Component’s functions (such as the required render() function).

The only method in React Component we must define in a class component is render(). The other methods (ex componentDidMount() shown below) are optional. Render is invoked whenever the component needs to update and a component is updated whenever there is a change in the components state or props .

Function Component

A functional component is just a JavaScript function which accepts props as and returns a React element. It is stateless unless React Hooks are used. They are usually used for presentational purposes. The below example is a presentational component that takes in props and creates a button that contains the data from props.

Summary

  • Class components are stateful, contain logic and have lifecycle functions

References

Lifelong Learner