Home  >  Article  >  Web Front-end  >  Avoiding Unnecessary Rerenders in React with Multiple States

Avoiding Unnecessary Rerenders in React with Multiple States

DDD
DDDOriginal
2024-10-10 12:24:02243browse

Evitando Re-renderizações Desnecessárias em React com Múltiplos Estados

It is common to use states to control different parts of the interface. However, if not managed well, multiple states can cause unnecessary re-renders, affecting system performance.

Problem: Too many states === Too many re-renders

Let's imagine that we have a component that manages a user's data. We can declare these states independently, like this:

const UserComponent = () => {
  const [name, setName] = useState('');
  const [age, setAge] = useState(0);
  const [address, setAddress] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [occupation, setOccupation] = useState('');

  // Funções de atualização dos estados
  const updateName = (newName) => setName(newName);
  const updateAge = (newAge) => setAge(newAge);
  // e assim por diante...

  return (
    ...
  );
};

Here we have 6 independent states, every time one of these states is updated, the entire component is re-rendered, now imagine that we need to update the 6 states... yes, we renders this component 6 times.

Solution: Create only 1 state regarding user information

One way to mitigate this problem is to consolidate all states into a single object. Instead of having separate states, we can keep all user information in one state, it would look like this:

const UserComponent = () => {
  const [user, setUser] = useState({
    name: '',
    age: 0,
    address: '',
    email: '',
    phone: '',
    occupation: ''
  });

  // Função para atualizar o estado do usuário
  const updateUser = (newData) => {
    setUser((prevState) => ({
      ...prevUser,
      ...newData,
    }));
  };

  return (
    ...
  );
};

Now, instead of having a function for each state, we have the updateUser function, which receives only the desired changes and combines them with the previous state using the spread operator (...). This allows you to update only a part of the state, while the rest remains unchanged.

If you want to change just 1 piece of information about the object, do this:

setUser((prevState) => ({...prevState, age: 25}))

Difference

When we use separate states, each individual state change causes a re-render of the component. When we consolidate all states into a single object, we still have a single re-render, but it only happens once, even if multiple parts of the object change.

Advantages

- Reduction of Re-renders: By consolidating states, we avoid multiple unnecessary re-renders, improving performance.
- Easier Maintenance: It is easier to manage user information in a single state, simplifying the code and making it more readable.
- Partially Controlled Updates: We can only change the parts of the state that need to be modified, without touching the rest.

That's it! I hope I helped!!!
Although I'm still developing, but here's my portfolio: https://lucaslima.vercel.app (I hope that when you access it, it's ready hahhaha)

Success! ?

The above is the detailed content of Avoiding Unnecessary Rerenders in React with Multiple States. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn