Skip to content

Bug: the order of effect and cleanup in Parent and Child component is weird #19482

@xialvjun

Description

@xialvjun

React version: v16.12.0

Steps To Reproduce

  1. just as the code example shows: just click the button 6 times respectively and see the console

Link to code example:
https://stackblitz.com/edit/react-effect-order-matters?file=index.js

The current behavior

useEffect logs: cpcc*1 + ppcc*n + pppc*1
useLayoutEffect logs: cpcp*(1+n) + cppc*1

The expected behavior

both useEffect and useLayoutEffect should log: cppc*(1+n+1)

Why I need a stable effect and cleanup order

There is a vanilla js package mapbox-gl whose use case is:

import mapboxgl from 'mapbox-gl';
var container = document.querySelector('#map');
var map = new mapboxgl.Map({ container });

map.on('load', function () {
  // every thing should be done after load
  map.addSource('route_source', route_source_data);
  map.addLayer({
    source: 'route_source',  // the layer relies on the source
    id: 'route_layer',
    ...other_layer_config,
  });
  // ...;
  do_many_things();
  // ...;
  // you must remove the layer before removing the source
  map.removeLayer('route_layer');
  map.removeSource('route_source');
});

Then I want to make a react version:

var vdom = (
  <Map opts={x}>
    <Source opts={xx}>
      <Layer opts={xxx}></Layer>
    </Source>
  </Map>
)

But since the order of react effect and cleanup in parent and child component is not stable (well, it' stable but it's weird), things became complex.

I think the effect and cleanup order matters because there are dependency relations between parent and child components.

And react should handle it.

There are some related(maybe) issues:
#16728
#17080

And the react lifecycle order is works right: https://stackblitz.com/edit/react-lifecycle-effect-order-right?file=index.js

Metadata

Metadata

Assignees

No one assigned

    Labels

    Resolution: StaleAutomatically closed due to inactivityStatus: UnconfirmedA potential issue that we haven't yet confirmed as a bug

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions