Functional Components React - updating a state causes the entire page to re-render
P粉180844619
2023-08-17 14:19:48
<p>Thank you very much for your help in advance.
I'm not sure why when I update the <code>percentageDone</code> state in <code>loadDataFunction()</code> it updates <code>RenderData1Component</code> when in fact it It shouldn't be like this. Shouldn't it only update when data1 changes? </p>
<p>I have a piece of code like this. </p>
<pre class="brush:php;toolbar:false;">const [loading, setLoading] = useState(true);
const [data1, setData1] = useState(null);
const [percentageDone, setPercentageDone] = useState(0);
LoadDataFunction(){
// Call multiple apis (let's say there are 10) in one promise and call setPercentageDone() when each api completes.
}
useEffect( () => {
LoadDataFunction()
},[])
useEffect( () => {
if (condition satisfied) {
LoadDataFunction() // Reload the latest data
}
}, [condition])
return (
loading ? percentageDone
: <RenderData1Component data={data1}>
)</pre>
<p>I only want to update <code><RenderData1Component data={data1}></code> when the <code>data1</code> state is updated, not <code>percentageDone< /code>. But whenever I update <code>setPercentageDone()</code>, it also triggers a re-rendering of <code><RenderData1Component data={data1}></code>. </p>
I'm not sure, but this might help you.
Possibly you are giving multiple conditions, which may cause problems. Please check this out too.