This post is one in a series in which we take React code that a less-experienced developer would write and improve it so that it resembles more what a professional would write. In the first part of the series, we converted a class component to a function component.
Today we're covering best practices for naming and using flags that you pass into components. Please check out the first part of the series to see the junior code and the refactored code.
Whenever you pass a boolean as an argument to a function, it is likely that the code can be better. The big reason is that it is hard to understand what effect that argument has on the function. This type of code is called a code smell. It is not a bug, but it indicates that there is a deeper problem in the program.
If you want to learn more about code smells, we would highly recommend reading the book Clean Code. You might disagree with some of the things he argues, but the book is worth reading once in your life. In the book, he lists lots of examples of code smells, and this type is called selector argument. If you encounter a situation where you want to use a boolean as a flag, you probably should split the function into two different functions.
Before I show you how to split this code into two functions, I will explain how you can make the code better if you want to keep using the boolean as a flag.
When passing a boolean into a function, one problem is that you don't know what that boolean means. The cheapest fix is to create a variable.
es6 lets you unpack the arguments passed into a function, and we can leverage that here. This approach is a slight improvement because it takes one fewer line of code.
The above two solutions are okay when the function is super simple. However, a lot of people would argue that we should always have two different functions. They would reason that the
getData function does two different things depending on whether it is the initial load or not, so it is better to split this function into two.
In the refactored, senior version of the code we split
loadMoreSameCategoryImages. Now it is totally clear what each function is doing!