Skip to content

Commit

Permalink
Always trigger componentWillUnmount in StrictMode (facebook#26842)
Browse files Browse the repository at this point in the history
<!--
  Thanks for submitting a pull request!
We appreciate you spending the time to work on these changes. Please
provide enough information so that others can review your pull request.
The three fields below are mandatory.

Before submitting a pull request, please make sure the following is
done:

1. Fork [the repository](https://github.com/facebook/react) and create
your branch from `main`.
  2. Run `yarn` in the repository root.
3. If you've fixed a bug or added code that should be tested, add tests!
4. Ensure the test suite passes (`yarn test`). Tip: `yarn test --watch
TestName` is helpful in development.
5. Run `yarn test --prod` to test in the production environment. It
supports the same options as `yarn test`.
6. If you need a debugger, run `yarn test --debug --watch TestName`,
open `chrome://inspect`, and press "Inspect".
7. Format your code with
[prettier](https://github.com/prettier/prettier) (`yarn prettier`).
8. Make sure your code lints (`yarn lint`). Tip: `yarn linc` to only
check changed files.
  9. Run the [Flow](https://flowtype.org/) type checks (`yarn flow`).
  10. If you haven't already, complete the CLA.

Learn more about contributing:
https://reactjs.org/docs/how-to-contribute.html
-->

## Summary

<!--
Explain the **motivation** for making this change. What existing problem
does the pull request solve?
-->
In StrictMode, React currently only triggers `componentWillUnmount` if
`componentDidMount` is defined. This would miss detecting issues like
initializing resources in constructor or componentWillMount, for
example:
```
class Component {
  constructor() {
     this._subscriptions = new Subscriptions();
  }
  componentWillUnmount() {
     this._subscriptions.reset();
  } 
}
``` 

The PR makes `componentWillUnmount` always run in StrictMode.


## How did you test this change?

<!--
Demonstrate the code is solid. Example: The exact commands you ran and
their output, screenshots / videos if the pull request changes the user
interface.
How exactly did you verify that your PR solves the issue you wanted to
solve?
  If you leave this empty, your PR will very likely be closed.
-->
`yarn test ci`
  • Loading branch information
tyao1 authored and AndyPengc12 committed Apr 15, 2024
1 parent 76158e3 commit 21817df
Show file tree
Hide file tree
Showing 3 changed files with 138 additions and 25 deletions.
37 changes: 16 additions & 21 deletions packages/react-reconciler/src/ReactFiberClassComponent.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import type {Fiber} from './ReactInternalTypes';
import type {Lanes} from './ReactFiberLane';
import type {UpdateQueue} from './ReactFiberClassUpdateQueue';
import type {Flags} from './ReactFiberFlags';

import {
LayoutStatic,
Expand Down Expand Up @@ -897,11 +896,10 @@ function mountClassInstance(
}

if (typeof instance.componentDidMount === 'function') {
let fiberFlags: Flags = Update | LayoutStatic;
if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) {
fiberFlags |= MountLayoutDev;
}
workInProgress.flags |= fiberFlags;
workInProgress.flags |= Update | LayoutStatic;
}
if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) {
workInProgress.flags |= MountLayoutDev;
}
}

Expand Down Expand Up @@ -971,11 +969,10 @@ function resumeMountClassInstance(
// If an update was already in progress, we should schedule an Update
// effect even though we're bailing out, so that cWU/cDU are called.
if (typeof instance.componentDidMount === 'function') {
let fiberFlags: Flags = Update | LayoutStatic;
if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) {
fiberFlags |= MountLayoutDev;
}
workInProgress.flags |= fiberFlags;
workInProgress.flags |= Update | LayoutStatic;
}
if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) {
workInProgress.flags |= MountLayoutDev;
}
return false;
}
Expand Down Expand Up @@ -1018,21 +1015,19 @@ function resumeMountClassInstance(
}
}
if (typeof instance.componentDidMount === 'function') {
let fiberFlags: Flags = Update | LayoutStatic;
if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) {
fiberFlags |= MountLayoutDev;
}
workInProgress.flags |= fiberFlags;
workInProgress.flags |= Update | LayoutStatic;
}
if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) {
workInProgress.flags |= MountLayoutDev;
}
} else {
// If an update was already in progress, we should schedule an Update
// effect even though we're bailing out, so that cWU/cDU are called.
if (typeof instance.componentDidMount === 'function') {
let fiberFlags: Flags = Update | LayoutStatic;
if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) {
fiberFlags |= MountLayoutDev;
}
workInProgress.flags |= fiberFlags;
workInProgress.flags |= Update | LayoutStatic;
}
if (__DEV__ && (workInProgress.mode & StrictEffectsMode) !== NoMode) {
workInProgress.flags |= MountLayoutDev;
}

// If shouldComponentUpdate returned false, we should still update the
Expand Down
10 changes: 6 additions & 4 deletions packages/react-reconciler/src/ReactFiberCommitWork.js
Original file line number Diff line number Diff line change
Expand Up @@ -4572,10 +4572,12 @@ function invokeLayoutEffectMountInDEV(fiber: Fiber): void {
}
case ClassComponent: {
const instance = fiber.stateNode;
try {
instance.componentDidMount();
} catch (error) {
captureCommitPhaseError(fiber, fiber.return, error);
if (typeof instance.componentDidMount === 'function') {
try {
instance.componentDidMount();
} catch (error) {
captureCommitPhaseError(fiber, fiber.return, error);
}
}
break;
}
Expand Down
116 changes: 116 additions & 0 deletions packages/react-reconciler/src/__tests__/StrictEffectsMode-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,47 @@ describe('StrictEffectsMode', () => {
assertLog(['componentWillUnmount']);
});

it('invokes componentWillUnmount for class components without componentDidMount', async () => {
class App extends React.PureComponent {
componentDidUpdate() {
Scheduler.log('componentDidUpdate');
}

componentWillUnmount() {
Scheduler.log('componentWillUnmount');
}

render() {
return this.props.text;
}
}

let renderer;
await act(() => {
renderer = ReactTestRenderer.create(<App text={'mount'} />, {
unstable_isConcurrent: true,
});
});

if (supportsDoubleInvokeEffects()) {
assertLog(['componentWillUnmount']);
} else {
assertLog([]);
}

await act(() => {
renderer.update(<App text={'update'} />);
});

assertLog(['componentDidUpdate']);

await act(() => {
renderer.unmount();
});

assertLog(['componentWillUnmount']);
});

it('should not double invoke class lifecycles in legacy mode', async () => {
class App extends React.PureComponent {
componentDidMount() {
Expand Down Expand Up @@ -590,4 +631,79 @@ describe('StrictEffectsMode', () => {
'useEffect unmount',
]);
});

it('classes without componentDidMount and functions are double invoked together correctly', async () => {
class ClassChild extends React.PureComponent {
componentWillUnmount() {
Scheduler.log('componentWillUnmount');
}

render() {
return this.props.text;
}
}

function FunctionChild({text}) {
React.useEffect(() => {
Scheduler.log('useEffect mount');
return () => Scheduler.log('useEffect unmount');
});
React.useLayoutEffect(() => {
Scheduler.log('useLayoutEffect mount');
return () => Scheduler.log('useLayoutEffect unmount');
});
return text;
}

function App({text}) {
return (
<>
<ClassChild text={text} />
<FunctionChild text={text} />
</>
);
}

let renderer;
await act(() => {
renderer = ReactTestRenderer.create(<App text={'mount'} />, {
unstable_isConcurrent: true,
});
});

if (supportsDoubleInvokeEffects()) {
assertLog([
'useLayoutEffect mount',
'useEffect mount',
'componentWillUnmount',
'useLayoutEffect unmount',
'useEffect unmount',
'useLayoutEffect mount',
'useEffect mount',
]);
} else {
assertLog(['useLayoutEffect mount', 'useEffect mount']);
}

await act(() => {
renderer.update(<App text={'mount'} />);
});

assertLog([
'useLayoutEffect unmount',
'useLayoutEffect mount',
'useEffect unmount',
'useEffect mount',
]);

await act(() => {
renderer.unmount();
});

assertLog([
'componentWillUnmount',
'useLayoutEffect unmount',
'useEffect unmount',
]);
});
});

0 comments on commit 21817df

Please sign in to comment.