Summary of 7 pitfalls when using react

Summary of 7 pitfalls when using react

React is a very popular front-end framework. Today we explore seven points that React developers should pay attention to.

1. Component bloat

React developers don’t create enough components as necessary. This problem is not limited to React developers, but also affects many Vue developers.

Of course, we are talking about React now.

In React, we can create a component with a lot of content to perform our various tasks, but it is best to keep the components concise - one component is associated with one function. This not only saves your time, but also helps you locate the problem well.
For example, the TodoList component below:

// ./components/TodoList.js

import React from 'react';

import { useTodoList } from '../hooks/useTodoList';
import { useQuery } from '../hooks/useQuery';
import TodoItem from './TodoItem';
import NewTodo from './NewTodo';

const TodoList = () => {
  const { getQuery, setQuery } = useQuery();
  const todos = useTodoList();
  return (
    <div>
      <ul>
        {todos.map(({ id, title, completed }) => (
          <TodoItem key={id} id={id} title={title} completed={completed} />
        ))}
        <NewTodo />
      </ul>
      <div>
        Highlight Query for incomplete items:
        <input value={getQuery()} onChange={e => setQuery(e.target.value)} />
      </div>
    </div>
  );
};

export default TodoList;

2. Change the state directly

In React, state is supposed to be immutable. If you modify the state directly, it will cause performance problems that are difficult to fix.
For example, the following example:

const modifyPetsList = (element, id) => {
  petsList[id].checked = element.target.checked;
  setPetsList(petList)
}

In the above example, you want to change the checked key in the array object. But you have a problem: because the object was changed using the same reference, React can't observe that and trigger a re-render.

To solve this problem, we should use the setState() method or the useState() hook.

We rewrite the previous example using the useState() method.

const modifyPetsList = (element, id) => {
  const { checked } = element.target;
  setpetsList((pets) => {
    return pets.map((pet, index) => {
      if (id === index) {
        pet = { ...pet, checked };
      }
      return pet;
    });
  });
};

3. The props should pass a numeric value but a string is passed, and vice versa

This is a very minor error and should not occur.
For example, the following example:

class Arrival extends React.Component {
  render() {
    return (
      <h1>
        Hi! You arrived {this.props.position === 1 ? "first!" : "last!"} .
      </h1>
    );
  }
}

Here === is invalid for the string '1'. To solve this problem, we need to wrap it with {} when passing props values.
The corrections are as follows:

// ❌
const element = <Arrival position='1' />;

//✅
const element = <Arrival position={1} />;

4. Key is not used in list component

Suppose we need to render the following list items:

const lists = ['cat', 'dog', 'fish'];

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

Of course, the above code works. When the list is large and needs to be modified, it will cause rendering problems.

React keeps track of all list elements on the Document Object Model (DOM). There is no record to tell React what happened to the list.

To solve this problem, you need to add keys to your list elements. Keys give each element a unique identity, which helps React determine which items have been added, removed, or modified.
as follows:

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

5. setState is an asynchronous operation

It's easy to forget that state in React operates asynchronously. If you try to access a value right after setting it, you might not be able to get the value right away.
Let’s look at the following example:

handlePetsUpdate = (petCount) => {
  this.setState({ petCount });
  this.props.callback(this.state.petCount); // Old value
};

You can use the second parameter of setState(), the callback function to handle it. for example:

handlePetsUpdate = (petCount) => {
  this.setState({ petCount }, () => {
    this.props.callback(this.state.petCount); // Updated value
  });
};

6. Frequent use of Redux

In large React apps, many developers use Redux to manage global state.
While Redux is useful, it is not necessary to use it to manage every piece of state.
If our application does not have parallel level components that need to exchange information, then there is no need to add additional libraries to the project. For example, when we want to change the state of a form button in a component, we give priority to the state method or the useState hook.

7. Component names do not begin with a capital letter

In JSX, components that start with lowercase will be compiled down to HTML elements.

So we should avoid the following:

class demoComponentName extends React.Component {
}

This will result in an error: If you want to render a React component, it needs to start with a capital letter.
Then you have to write it like this:

class DemoComponentName extends React.Component {
}

Afterword

The above content is extracted from Top 10 mistakes to avoid when using React. It uses a paraphrase approach to extract 7 more practical contents.

This concludes this article about 7 cases of avoiding pitfalls when using react. For more relevant react pitfalls, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • A simple guide to React server rendering (SSR)
  • react-router4 on-demand loading (filling the pit)
  • Detailed explanation of the pitfalls encountered by React native fetch
  • React Router v4 Getting Started Guide (Summary)
  • ReactNative FlatList usage and pitfalls package summary
  • A brief discussion on the pitfalls of React Native packaging apk
  • Detailed explanation of the use of react-native-fs plug-in and the pitfalls encountered
  • Detailed guide to upgrading react-router 4
  • ReactNative stepping on the pit to configure the debugging port solution

<<:  Add crontab scheduled tasks to debian docker container

>>:  MySQL 8.0.12 winx64 decompression version installation graphic tutorial

Blog    

Recommend

How to encapsulate axios in Vue

Table of contents 1. Installation 1. Introduction...

Detailed explanation of Vue-router nested routing

Table of contents step 1. Configure routing rules...

MySQL 8.0.19 Installation Tutorial

Download the installation package from the offici...

Two ways to build Docker images

Table of contents Update the image from an existi...

How to use the debouce anti-shake function in Vue

Table of contents 1. Anti-shake function 2. Use d...

How to solve the mysql insert garbled problem

Problem description: When inserting Chinese chara...

How to use nginx to intercept specified URL requests through regular expressions

nginx server nginx is an excellent web server tha...

Detailed process record of nginx installation and configuration

Table of contents 1 Introduction to nginx 1 What ...

Thinking about grid design of web pages

<br />Original address: http://andymao.com/a...

Query the data of the day before the current time interval in MySQL

1. Background In actual projects, we will encount...