The React component architecture allows the developer to break up a user interface into small, standalone units that are easier to manipulate and debug. The React library provides developers with several options for writing components, and I often find it difficult to decide which component format to use for a given block of code. In order to demystify the variety of components in React, I'll attempt to compare and contrast the structure of each type and describe their best use case.
Although JSX may look like regular HTML, it’s important to remember that they are not technically the same. Now that we’ve had a brief introduction to React components, let’s take a look at the different ways we can write them.
Functional components are the most basic type of component in React. They are often referred to as “stateless” components or presentational components. You are unable to define state within functional components as there is no context for the JS this keyword in a function.
Functional components are an efficient way to render content to the page when defining state is not necessary. They are also advantageous and quicker to write if a component doesn’t require much logic. Here's an example of a functional component that renders "Hello, World" to the screen:
Another thing to note about functional components in React is that unlike their class counterparts, you cannot use React’s lifecycle methods. Lifecycle methods let you control the way your components are rendered or removed from the page by specifying a series of events for each individual component.
In the following example, I was building a page to display photos and information for various pigs. I used state in the Pig Container class to store a list of pig objects, and then rendered a Pig component for each pig. This highlights the usefulness of React classes as "container components":
Although class components often have state, they don’t have to. Thus, it’s possible for a React class component to act as either a stateful or stateless component. We can take our functional component example from earlier and easily change it to a stateless class component:
I had trouble figuring out when to use a class component and when to use a functional component. In the end, it really comes down to what you need your component to do. If your component will use state and have complex logic, use a class component. If you just need a bit of code to render something to the page, the functional component will be your best choice. I hope this helps clear up some of the confusion surrounding React components!