Some JavaScript/React coding practices to avoid

In my years developing front-end applications both individually and as part of a team, there are some practices I’ve noticed which I really dislike. Some are personal preferences while others are also identified by the industry. I’ve developed front-end applications with several frameworks/libraries and these issues arise all the time. However, some of the points mentioned below are peculiar to React even though they could occur with other frameworks. I’ll update this list from time to time to include more points.

Strive to avoid:

  1. Having Ambiguous/unclear variable names
  2. Having unused props/state fields
  3. Having extremely large components – Be modular and encapsulate special logic (separation of concerns)
  4. Having a very large render() method – Still connects to the principle of modularity. Your render method should be as small as possible. Break down certain aspects of the view into separate components or functions.
  5. Not having interface definitions for component props or function parameters – It defeats the purpose of using TypeScript or Flow.
  6. Repeating components during conditional rendering instead of placing the condition in the attribute that changes.
  7. Code repetition – Use a service to encapsulate common logic.
  8. Repeating nested objects during null checks instead of using JavaScript optional chaining. Read for more information.
  9. Mutating Redux state – VERY DANGEROUS. Always make a deep copy of your redux state before making changes. Read for more information.
  10. Hard-coding state values for values that ought to change.
  11. Placing too much logic in the reducer – This makes it difficult to trace what is being updated and where. It’s better to extract API response from your action-creators before passing data to the reducer.
  12. Using regular CSS files for styling – Use CSS modules or styled-components instead to prevent style conflicts. (I didn’t encounter this issue much in Angular due to the shadow DOM pattern), but still, there are ways to ensure you don’t have style conflicts.
  13. Updating API request body and Redux store from several components – This makes it hard to trace what is going on. Try to have just 1 single source of truth in your code.

Before pushing your code or creating a pull request, also check to remove:

  1. Console logs/errors
  2. Unused methods/functions
  3. Unused files
  4. Unused import statements

By adhering to these and other best practices, we gain the following:

  1. Smaller bundle size
  2. Increased application speed
  3. More maintainable code – very useful when debugging
  4. More predictable app behavior – very useful when debugging
  5. Better code quality – very useful when debugging

Leave a Reply

Your email address will not be published. Required fields are marked *