In my React app, I will implement useState multiple times in a single component. Then in my useEffect I will change the state of several of these:
import React, { useState, useEffect } from 'react';
const Projects = React.memo(function (props) {
const [someState1, setSomeState1] = useState(false);
const [someState2, setSomeState2] = useState(false);
const [someState3, setSomeState3] = useState(false);
useEffect(() => {
if (someConditionMet) {
setSomeState1(true);
setSomeState2(true);
setSomeState3(true);
}
});
if (initialized) {
return <div>Hello World</div>;
});
What I notice is that each time setSomeState1, setSomeState2, setSomeState3 is called, the entire component gets re-rendered for each of these calls. I really only want it to re-render once when useEffect has completed. Is there a way in React to prevent the rendering from happening multiple times when multiple states are changed within useEffect?
You will need to add a dependency array to your useEffect so that the condition will be called only once
useEffect(() => {
if (someConditionMet) {
setSomeState1(true);
setSomeState2(true);
setSomeState3(true);
}
},[]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With