React Function Components vs Class Components

Meghan Elizabeth
2 min readJul 5, 2021
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
  • Function components are stateless (unless React Hooks are used), their only job is to display data and they don’t have access to lifecycle functions

References

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Responses (1)

Write a response

please delete this artcle