Most Common Mistakes To Avoid In React Development

Some mistakes have become common among developers working on React applications. These mistakes might be the result of an oversight, pressure to meet a deadline, or an absence of experience with React/JavaScript. Here you came to know with some common mistakes that you should avoid in react development.

Most common mistakes to avoid in react development

1. Not creating enough components-

One mistake that React developers frequently make is that they don’t create enough components. Generally, there are two different ways of writing applications: putting everything in one place (monolith), or partitioning everything into smaller pieces (micro-services). To build this dashboard effectively with the use of React, we have to consider it as a set of components that form a page instead of an entire page itself. That way, we can create various sets of components that — when assembled — make up the entire page. This technique saves your time, however it also saves you a lot of stress while debugging since you’ll instantly know which component is associated with each error.

2. Writing logic in components-

While looking for an appropriate method to create components for reusability, the presentational and container component creation pattern is often one of the first to appear.

Presentational components are related with how things look, while container components are related with how things work. A common mistake you’ll see in React applications is that presentation markup and application logic are fused into one component. The drawback of this approach is that you cannot easily reuse any of the components or logic without copying and pasting. If you use the presentational and creation pattern, you can achieve reusability of both the markup and logic more effectively. You can also make UI changes without messing up the behavior.

Let us see the components below:

This is a component that is just needed to get data from props and show it. It is a presentational component.

const Books = props => (
  <ul>
    {props.books.map(book => (
      <li>{book}</li>
    ))}
  </ul>
)

This books component manages and stores its own data, and uses the presentational component books above to show it.

class BooksContainer extends React.Component {
  constructor() {
    this.state = {
      books: []
    }
  }

  componentDidMount() {
    axios.get('/books').then(books =>
      this.setState({ books: books }))
    )
  }

  render() {
    return <Books books={this.state.books} />
  }
}

3. Mutating state variables

Mutation is the ability to change something. Consider the following state:

const person = {
   name : "John",
   gender  : "Male",
}

If you create a new variable in your application at some point and assign the person object to it with the aim of changing it, you might be shocked by the result:

const newPerson = person
newPerson.name = "Jane"
newPerson.gender  = "Female"

If you attempt to log both the person and newPerson object, you’ll see that both now reflect the most recent value that was set. This frequently clarifies unusual component behavior. To solve this, you can use the .slice() method or the ES6 spread administrator ES6 spread operator.

However, the best approach is immutability. You can either implement it yourself, or use Immutable.js and immutability-helper, which is recommended by the React team.

4. Not using absolute paths-

If you have ever worked on a React application that has numerous components, images, CSS files, and other files, you’ll agree that importing files from various directories can be tedious. Commonly, we’ll import files this way:

../../../importone.js
../../../importtwo.js

We have seen that it isn’t neat, and changing the directory of a file will cause the import to fail. With the release of Create React App 3, we would now be able to utilize absolute import paths. To do this, create a jsconfig.json file in your root directory with the following:

// jsconfig.json
{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}

Now, you can import your files this way:

import React from 'react';
import { LINKS } from 'helpers/constants';
import Button from 'components/Button/Button';

function App() {
  return (
    <>
      <Button>
        This is my button
      </Button>

      <a href={LINKS.ABOUT}>About Us</a>
    </>
  );
}
export default App;

Not only is this cleaner, however it also implies you don’t have to update the way in your code after changing the location of a file. Get familiar with CRA V3 here.

5. Not using key on a listing component-

We regularly run into situations where we would need to render a list of things. The code seems to be like this:

const lists = ['one', 'two', 'three'];

render() {
  return (
    <ul>
      {lists.map(listNo =>
        <li>{listNo}</li>)}
    </ul>
  );
}

For smaller applications, this may work. When working with enormous lists, you’ll run into render issues when you attempt to modify or delete an item from the list.

react monitors each of the list elements on the DOM. Without it, it would not know what has changed in the list item. To fix that, you have to add a key to all your list elements like below:

<ul>
  {lists.map(listNo =>
    <li key={listNo}>{listNo}</li>)}
</ul>

6. Not writing unit tests-

This is one of the most well-known mistakes out there. It’s frequently overlooked because applications can still technically work without unit tests. A unit test enables you to test parts of your application freely to ensure a specific functionality works as expected.

For example, you can write a unit test to check if a prop went to a component was rendered on the browser. You may wonder why you’d write such a small test. Some of the time you expect your prop should show appropriately after writing your components, yet occasionally a conflicting CSS style may block it from displaying. 

Writing a unit test saves you the time you’d spend finding that bug by pointing it out immediately. They assist you with debugging rapidly across your application.

7. Not using prop-types-

We regularly observe incorrect data types being passed around in applications. For instance, say you need to pass a number 2 by means of props to another component. Frequently, you’d see it done like this:

<MyComponent value="2" />

This sends the value 2 to MyComponent as a string rather than a number. To send it as a number, write it like follow:

<MyComponent value={2}/>

Defining the types via the prop-types package is the most reliable method for ensuring you send the correct props.

Prop-types are used to document the intended types of properties passed to components. React will check props passed to your components against those definitions, and warn in development if they don’t coordinate.

8. Not using helper classes or functions-

This is most common mistake noticed in many React applications.

Also to reusable components, we also have reusable functionalities in our applications. This functionality is frequently hardcoded on a components to component basis, which prompts inefficient and inconsistent behavior between similar components.

All container components contain logic to get a resource, save it to state, and deal with errors. Many times, this behavior is the same from one container component to another, however it can act inconsistently when not written appropriately. 

Consider the above example where we make an API call to get a resource, set the state, and also handle errors.

If we extract that behavior to a helper class or function, we can reuse a similar logic for API calls, setting state, and error handling.

9. Using Redux or Flux to manage all your application states-

In greater React applications, many developers use Redux or Flux to manage global state. This is extremely helpful, particularly when different parts of the application will benefit from having a shared state.

In any case, it’s inadvisable to utilize Redux or Flux to deal with each state in your application.

Take, for example, a form components. If we need the state of a check button to consistently be checked whenever we visit it, the best approach is to manage it using local state method or useState (for Hooks) instead of using Redux or Flux.

10. Not using React and Redux dev tools-

Applications consistently get buggy after a while. Debugging is regularly a great deal of work, since most of the time many components are involved. With React dev tools, you can assess the rendered tree of React elements, which is incredibly helpful for seeing how different components build up a page.

The Redux dev tools likewise accompany a host of features that let you see each activity that has occurred, see the state changes these actions caused, and travel back to before specific actions occurred. You can include React dev tools as either a dev dependency or as a browser extension. Using them will save you a great deal of development time.

Final words-

From these, you came to know about some common mistakes in react development. You can develop a better web solution with react by avoiding such mistakes. There can be few others also. 

Avoiding such errors can lead you to the success of a development that you deserve. If you are still facing some difficulty with react development, consult with solace experts team. Team is well proficient in new technology trends to give you the best web solution with react. We will be happy to help you.