React Patterns (Part 1): Functional Components

Wesley Rast
2 min readNov 16, 2018

--

React has a lot of patterns that new developers need to memorize when they’re getting started. I’m going to go through some of them that I’ve found useful over the past few years, starting with those I think are the easiest to grasp and the most useful, then give code examples that you can use as templates for your own work.

Functional Components

There’s three ways to declare a React component: as a functional component, as an ES6 class, and calling React.createElement. Of these, the functional component is the most terse and is the easiest to understand:

Thanks to ES6 arrow functions, the syntax can be just that simple. Since we haven’t used the props parameter here, you could simplify it even further by replacing the props with (), but I’ve found it’s better practice when working with large teams to leave the props parameter name there. Arrow function return the result of single-statement function bodies by default, so we can omit the otherwise obligatory return as well.

Here’s another example with a bit more meat on it. You can consider the below as a good template to start with when you need a functional component.

Assigning defaultProps and propTypes (you do assign propTypes, don’t you?) can be handled in the same way as component classes.

Functional components are great for simple rendering cases, and the code they generate through a transpiler is very small, which is great for our end user’s download speed, particularly if we’re building hundreds of components.

The downside to functional components is that they are inherently stateless. Referring to this will return undefined (the default behavior in ES6 functions), or when trying to render the value in JSX as I do here, an empty string.

Furthermore, you can’t utilize the component’s constructor to initialize it, nor call any of the component’s lifecycle events like getDerivedStateFromProps() or componentShouldUpdate(). This means that functional components are a poor choice when you’re doing anything but rendering simple content in response to props changes.

--

--