Without further ado, let’s look at some of the most common mistakes React developers make.
Directly mutating the state
This mistake is usually made by beginners, but I’ve seen a few middle-seniority developers make it as well. In React class components, the state is an object. In functional components, it’s a variable. React has one big rule – you can not change (mutate) the state directly. This applies to state object (class components) as well as functional components. In class components, we use the setState() method to update the state. When it comes to functional components, we use the useState hook, which gives us the function to update a specific state variable. We always use that function to update the state. You can not directly update one of the properties of the state object, or set the variable to a different value manually.
For example, in this article the author explains how to implement expand and collapse feature in React.
Look at code examples and you’ll see that the developer never directly mutates the state. He uses the function returned by the useState() hook.
In React, it’s a common practice to capitalize component names. Many beginner developers don’t know this and even create components with the same name as some HTML elements, which leads to a lot of confusion. Some senior developers forget to capitalize component names as well, but it happens much less frequently than with beginner devs.
React developers capitalize the first letters of components to distinguish them from React elements. That way, JSX code is easier to read.
React developers who have not worked in a professional setting usually have messy folder structures. This happens because structure is not as important when you’re an independent freelancer, but it’s extremely important in the workforce.
So beginner developers, or seniors who are transitioning from freelance to corporate work, often make some mistakes organizing files. But this pattern usually goes away within a few months, when they accumulate experience of working in a professional setting.
Developers sometimes create ‘god components’ with a lot of fixed parts that are not flexible. This is similar to standard ‘HTML’ structure, and it doesn’t utilize component-based and flexible design of React.
A much better approach is to take a close look at components with a lot of code and moving parts, and break them up further into smaller components.
To sum up, everyone makes mistakes when building apps in React. The important thing is to learn from mistakes and improve every day, so you make less and less mistakes.