Functional vs Class Components in React

Chamikara Mendis
2 min readJan 22, 2023

--

Source: https://ms314006.github.io/

In react, there are two main ways to define a component: as a function or a class. These are known as functional components and class components, respectively.

Functional components are just Javascript functions that take in props and return a JSX element. They are simple and easy to understand and can be used for both presentational and container components. Here’s an example of a functional component.

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

On the other hand, class components are JavaScript classes extending React component class. They have a more complex structure but also more features, such as lifecycle methods and the ability to use the state. Here’s an example of a class component.

class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}

When deciding whether to use a functional or a class component, its essential to consider the specific requirements of your component. If you don't additional features, a functional component is the best choice for its simplicity and readability. However, If you need to use state or lifecycle methods, you’ll need to use a class component.

It’s worth noticing that with the introduction of hooks in React v16.8, functional components can now also have state and use lifecycle methods using hooks, In most cases, this allows you to use functional components instead of class components, making your codebase more straightforward and readable.

Another important difference between functional and class components is how they handle this keyword. in class components, this refers to the component instance and allows you to access props and state. However, this is not defined in functional components, so you need to pass props as an argument and use the directly. Functional components also have a slight performance advantage over class components because they don't have to deal with the overhead of creating an instance. However, this difference is usually insignificant. When it comes to testing, functional components are generally easier to test than class components. Because they are plain JavaScript functions, you can test them by passing in props and asserting the output. With class components, you need to create an instance and access the component’s internal state, which can be more complex.

--

--

No responses yet