Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent re-rendering when state is changed multiple times during useEffect

Tags:

reactjs

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?

like image 712
Johann Avatar asked Oct 24 '25 21:10

Johann


1 Answers

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);
     }
},[]);
like image 52
Frustrated Programmer Avatar answered Oct 26 '25 12:10

Frustrated Programmer