State and Lifecycle in React. Container and presentational components. React interview cheatsheet series
According to the official ReactJS documentation we can define React components in two ways:
- As a function
- or as a EC6 Class
A function components is the simpliest way to define a React JS component, and should be like:
It is simple function that accepts props as arguments and returns a React element.
A class component uses the ES6 class syntax to be written. The same component that above should looks like:
But, beyond syntax differences, which is the main difference between function and class components? Basically, and first at all, the states.
You can find more details again in official documentation about class components states and lyfecycle.
But to summarize, I would say that the main purpose to use ES6 class components instead of function components is just the use of states.
If you don't have states, and just use props, you can use function, you don't need to use a class based component. Even more when React 16.8 introduced the hooks, and you can use useState hook and useEffect hook which is similar to componentDidMount, componentDidUpdate and componentWillUnmount combined.
According to React Team, functional components are:
- Force you adopting good practices, separating container and presentational components forcing you to think better about states. You should use functional components if you are writing a presentational component.
- Performance benefits on functional components rather than class based components.