Home > Article > Web Front-end > Avoiding Unnecessary Rerenders in React with Multiple States
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.
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.
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}))
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.
- 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!