3 React Patterns That Can Be Anti-Patterns |#4

Flushen
2 min readNov 19, 2020

1. Not Using Forms for GET Requests

I see a lot of React components which do a ton of unnecessary state management to keep track of information. Oftentimes, these complicated queries can be simplified by using a powerful feature of HTML forms: <form action="GET">.

When you use a form, the browser will handle all of the state management and URL encoding for free. Using this trick will make your React code simpler, more maintainable, and easier to read. 🙌

Next time you find yourself managing a ton of state for a form, see if you and get away without using Javascript at all for managing state, and instead use HTML forms and your router of choice.

2. Never Using Class Components

If you are not aware, hooks are the new hotness in React. They are incredibly useful for handling state in functional components and oftentimes make React code simpler, and easier to read.

One pattern I have seen in React apps is using hooks and functional components for absolutely everything.

“When you have a hammer, everything looks like a nail.” 🔨

In my opinion, sometimes class components can be easier to comprehend and quicker to write.

Let’s be honest here. Which of these two examples do you find easier to read?

If you are like me, Example 1 is something I can glance at and immediately understand what it does. However, in Example 2, I had to reference the docs and a couple of blog posts to remember what useCallback does.

I’m not saying that you should never use hooks; in fact, I use React hooks all the time! But in certain cases, class components make your code more readable and maintainable.

If you have a functional component with a lot of helper methods or confusing hooks, consider using a class component to see if it is easier to understand.

3. Not Using CSS When It Makes Sense

Since React has such powerful JS functionality, sometimes it is easy to forget about traditional CSS styles.

One anti-pattern I have seen a lot is what I call over-reliance on conditional rendering. For example, it is incredibly easy to hide a component in 2 lines of JS in React:

However, this can often lead to jarring user experiences since components pop in and out of existence instantly. Instead, I prefer to use conditional classnames and CSS to create a smoother UX.

In this pattern, instead of hiding a component using an if statement, you can add a className prop which will hide the component using an animation.

Pro Tip: Check out Animate.css for some awesome, “just add water” CSS animations to use with this pattern.

Summary

Overall, I’d encourage all React developers to learn about all of the powerful features that the Web Platform has to offer. Oftentimes, they will make your components simpler, more maintainable, and more robust. Your team (and your customers) will thank you! ❤️

--

--