Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it acceptable to re-render the children 3 times in ReactJS?

Lets say I have 3 components connected in one parent one.

Pseudo example:

<div>
 <Parent />
 <ChildMetaData />
 <ChildData />
</div>

On click of <Parent /> I use the following function that's passed as a prop:

handleParentClick(tid,sifUser) {
    this.setState({
        tid : tid , 
        sifUser : sifUser
    },
    () => {
        this.loadChildRequestsFromServer();
        this.loadUserDataFromServer();
    });
}

State changes.

=> All 3 components re-render.

When my loadChildRequestsFromServer() finishes it changes state of global variable

=> All 3 components re-render.

When my loadUserDataFromServer() finishes it changes state of global variable

=> All 3 components re-render.

As you can see , when I click on my parent my components re-render 3 times. ( I check that by running console.log in one of the render function of the component, like <ChildData />.)

Is this an acceptable behavior , or am I doing something wrong?

I should note that both of the "load from server" functions are AJAX calls. And since loadChildRequestsFromServer() and this.loadUserDataFromServer() are chained together , maybe I shouldn't immediately update the state after the first function is over. But rather pass the data to the next function and update the it there.

like image 351
Paran0a Avatar asked Jun 05 '26 06:06

Paran0a


1 Answers

It is perfectly fine for your components to re-render 3 times.
Because there are 3 distinct states of your parent:

  1. without any ajax results
  2. with ajax results from first call
  3. with ajax results from both calls

React will filter out all unnecessary DOM-updates anyway, which is the main performance bottleneck. You could filter out unnecessary updates by implementing shouldComponentUpdate(). This will also prevent unnecessary executing of render() function.

(update) If the first child only needs first ajax call results, and the second child only needs second call results, then you could also considering giving each child state, and call each function from within its respective child.
That way, each child updates independently, and you get less render calls. Number of DOM updates will remain the same = minimal as compared to the original solution.

If you NEVER need the state with only results of one ajax call, then you can chain like you describe. But that would make any error handling much trickier.

like image 180
wintvelt Avatar answered Jun 07 '26 20:06

wintvelt