Functional vs. Stateful React.js Components
For those just getting started with React.js, it’s fairly common (in ES6 anyway) to see how to construct a React Component class and build your component from that class. It turns out we can also build React components as simple functions that return JSX. Simple functional components get props injected just as a class component does, so the general design rule is:
- If you need state, use a class.
- If you need to take advantage of component lifecycle methods, use a class.
- If you don’t need state and only need props or need nothing at all, use a functional component.
The Stateful Component
The “Stateful” component is a class that implements React.Component and has the capability to manage its own internal state using React. Although state management inside the class-based component is possible, I’ve seen many examples where developers are creating components as classes when they don’t use state at all. This is a great time to consider simpler functional components.
Stateful components have a set of functions that can be overridden allowing for different operations at the different points in the component’s lifecycle. It also typically has a constructor.
Here is an example of a React class that doesn’t use state, but does depend on props being provided. See line 15 for use of props.
The Pure Component
The simplest possible form of a stateless component might look something like this.
Below is an example of a more useful functional component. See lines 7 and 12 to see where the props are used, and note there is no internal function declared.
One can make even simpler functional components, of course, but at least this one shows us some import information.
- The props argument does get passed into the function.
- Functional components simply return something. It happens to typically be JSX.
- Inside the function, we can perform other operations before getting to the return statement, so it doesn’t have to be a “dumb” component just because we aren’t making use of state or class lifecycle methods.
- We can still make use of required PropTypes.
- We still export the component, no matter what the type.
I have an application in which I recently went back and did a conversion of all my “dumb” classes into functional components.
The design of my application got simpler. I’d encourage you to shift gears if you are using class components for every component you have and give functional components a try.