Bug: React.StrictMode causes AbortController to cancel

This issue has been tracked since 2022-09-16.

React version: 18.2

Steps To Reproduce

  1. import a hook that uses AbortController
  2. Without React.StrictMode the abort controller aborted = false
  3. With React.StrictMode the abort controller gets set to aborted = true
const useAbortController = (abortControllerProp, shouldAutoRestart = false) => {
  const abortController = useRef(abortControllerProp || initAbortController());

  useEffect(() => {
    if (shouldAutoRestart && abortController.current.signal.aborted) {
      abortController.current = initAbortController();
    }
  }, [abortController.current.signal.aborted, shouldAutoRestart]);

  useEffect(() => () => abortController.current.abort(), []);

  return abortController.current;
};

The current behavior

The "echoed" rendering of the component causes the the controller to go from aborted false -> true.

The expected behavior

I'm not sure if this is inherent to what react tests for in this mode, or something that can be expected to work.

eps1lon wrote this answer on 2022-09-17

This is intentional behavior added in React 18 to StrictMode. Effects are now double-invoked (including their cleanup) to ensure component state is reusable. You can learn more about it in https://reactjs.org/docs/strict-mode.html#ensuring-reusable-state

EdmundsEcho wrote this answer on 2022-09-17

@eps1lon I suspected as much. May I ask what the recommended approach is to manage the AbortController interface in context of StrictMode?

vkurchatkin wrote this answer on 2022-09-19

@EdmundsEcho the recommended approach it to just let it happen and make sure it works correctly

gaearon wrote this answer on 2022-09-19

The issue here is that your effect’s code isn’t symmetric. You shouldn’t implement cleanup in a separate effect — the effect that creates the controller should be the same one that destroys. Then an extra cycle wouldn’t break your code.

More Details About Repo
Owner Name facebook
Repo Name react
Full Name facebook/react
Language JavaScript
Created Date 2013-05-24
Updated Date 2022-10-03
Star Count 195560
Watcher Count 6648
Fork Count 40508
Issue Count 1111

YOU MAY BE INTERESTED

Issue Title Created Date Updated Date