5 React Anti-patterns Every Developer Must Know
Over the years, app development has gained quite the audience as companies huddle in to create world-class mobile apps.
Every mobile app requires a framework and since time immemorial, developers have been using the one and only React Native to create high-performance apps.
In this blog, we’ll take a look at some of the most crucial React anti-patterns that you ought to know as a developer. Here’s a rundown:
- Props Drilling: One issue you could encounter in a large project is having one component at the very top that holds your state and another deeply nested component that also needs to use that state. You typically give that state as a prop to a number of intermediate components up to that child, who doesn’t actually need it. Proper drilling is the term for this. You can resolve this using state management such as Redux, Context API, etc.
- Component Nesting: Refactoring your project may reveal another anti-pattern of component nesting. The main issue here is that every time the parent component is rendered, the child component will also be redefined, meaning it will receive a new memory address, which could cause performance problems and unexpected behaviour. It may be fixed by either not defining any child components at all or by removing them from the parent and passing the function as a prop.
- Props Plowing: Props Drilling is a vertical difficulty, but you may also experience Props Plowing, a horizontal issue. It is possible to wind up with components that have a variety of distinct props and a long, repetitive piece of code where each prop is named after the variable that was supplied to it. The solution for this is using spread operators.
- Useless Divs: You receive an error while attempting to return two sibling components together when defining a brand-new component. Due to the fact that each component can only have one root element, wrapping it in a div would be a completely acceptable solution. However, it results in a tonne of pointless divs in the markup. You can solve this using React’s built-in fragment component or you can use the shorthand syntax.
- Coupled State: It’s tempting to combine all of your data into a single object when working with the state hook in a component. The code appears clearer and can even appear more efficient since setState just needs to be called once. But you should be aware that every time you update the state with React 18, batching will happen automatically. Therefore, invoking setState more than once within a single function will not result in repeated re-renders. Therefore, it has little impact on performance, but more crucially, it makes it challenging to separate your code into customised hooks. So the solution for this would be extracting your logic into a custom hook.
Conclusion:
Knowing these vital React anti-patterns while undertaking React Native app development is a must for every skilled developer.