"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Avoiding Unnecessary Rerenders in React with Multiple States

Avoiding Unnecessary Rerenders in React with Multiple States

Published on 2024-11-07
Browse:921

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, each 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 changing the rest.

And that! 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! ?

Release Statement This article is reproduced at: https://dev.to/lucaslimasz/evitando-re-renderizacoes-desnecessarias-em-react-com-multiplos-estados-nae?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3