Skip to content

Bug: StrictMode reruns effects when a child is moved in an array #32561

Closed as duplicate
greptileai/react-mirror
#652

Description

@krispya

With strict mode on in React 19, when a keyed React element is moved in an array its effects are rerun, even if they have no dependencies. The same behavior is not done for elements that stay in place. This is different from React 18 where moving an element did not trigger rerunning effects.

I would like confirmation if this is intended or a bug, but I did not see it documented so I assume it is a bug.

React version: 19.0.10

Steps To Reproduce

Here is a repro in React 19: https://stackblitz.com/edit/react-ts-qmpiwmru?file=App.tsx,index.tsx
And the same in React 18: https://stackblitz.com/edit/react-ts-pzgjq9ay?file=App.tsx

The current behavior

All effects are rerun when a keyed React element is moved in a child array.

The expected behavior

No effects are run, like React 18.

Activity

  1. added
    Status: Unconfirmed
    on Mar 9, 2025
  2. annous246 commented on Mar 10, 2025

    @annous246

    I did run some tests ,

    • when you use only list reduction (reducedIds) in REACT 19 it dosent rerender ,
    • but when it comes to using only rotated ids with no reduction it rerenders ,
      • ->in my opinion new REACT 19 updates are much more strict on the virtual DOM comparaison on each change made to the order of keys per child element .

    • (this is evident when the last click that leaves you with the last child element dosent trigger a rerender due to elements order no changing after it),
      to prevent that "unecessary" rerender -> use mapping indexes as key values per element for order stability
    function MapComponent({ ids }: { ids: number[] }) {
      return (
        <>
          {ids.map((id,index) => (
            <Item key={index} id={id} />
          ))}
        </>
      );
    }
    

    I hope This Helps ❤️
  3. krispya commented on Mar 10, 2025

    @krispya
    Author

    I did run some tests ,

    * when you use only list reduction (reducedIds) in REACT 19 it dosent rerender ,
    
    * but when it comes to using only rotated ids with no reduction it rerenders ,
      
      * ->in my opinion new REACT 19 updates are much more strict on the virtual DOM comparaison on each change made to the order of keys per child element  .
    
    * **(this is evident when the last click that leaves you with the last child element dosent trigger a rerender due to elements order no changing after it)**, to prevent  that "unecessary" rerender -> use mapping indexes as key values per element for order stability
    
    function MapComponent({ ids }: { ids: number[] }) {
      return (
        <>
          {ids.map((id,index) => (
            <Item key={index} id={id} />
          ))}
        </>
      );
    }
    

    I hope This Helps ❤️

    I think this proves it is a bug as the fix you suggest is explicitly called out in the React docs as a pitfall because it creates unstable element-key references: https://react.dev/learn/rendering-lists#why-does-react-need-keys

    If you dig into react-reconciler it has four kinds of actions it can take on keyed elements: insert, move, stay or delete. Stay does not cause effects to run mount, as you point out, but move does. Insert is a mount and delete is an unmount. I don't believe move should cause effects to mount, like it did in React 18, and this looks like a regression.

  4. totomakers commented on Mar 14, 2025

    @totomakers

    Encounter the same issue. We have a Drag and drop list;

    With React18 - the effect are not rerun - key is set to a static ID comming from API.
    With React19 - effect are rerun

    React 18 behavior:

    output.webm

    React 19 behavior:

    output2.webm
  5. added
    Status: Unconfirmed
    and removed
    Status: Unconfirmed
    on Mar 31, 2025
  6. kassens commented on Mar 31, 2025

    @kassens
    Contributor

    The "double invoke effects" behavior is really just a simple test for components that their effects should be able to unmount and remount at any time.

    Not sure if this is easily avoidable, but overall, ideally components should not care about this extra call in dev/strict mode.

  7. krispya commented on Mar 31, 2025

    @krispya
    Author

    In my case the effect had no dependencies and was setting an initial value. I made the (false) assumption this effect would only run on mount, even if it ran twice, and so when it started rerunning other than on mount it was resetting the value. To fix this, as you suggest, I had to write defensive code where a ref kept track of if the effect had already run. It was a reminder that effects can really run at any time and there is no guarantee an effect with empty dependencies will run when you expect.

  8. totomakers commented on Apr 11, 2025

    @totomakers

    This is my effect code

     useEffect(() => {
        const controller = new AbortController()
    
        setDataChunks([])
        setMapLayersLoading((ids) => [...ids, { layerId: key, loaderId: _id }])
    
        const fetchPage = async (cursor?: string) => {
          const resp = await fetchChunk(
            {
              id,
              onTimeout,
              type,
            },
            { ...ctx, pagination: { after: cursor, first: ITEM_PER_CHUNK } },
            controller.signal,
          )
    
          const hasNextPage = resp?.hasNextPage || false
    
          if (resp) setDataChunks((current) => current.concat([resp.rows]))
          if (hasNextPage) await fetchPage(resp?.endCursor)
        }
    
        const start = async () => {
          try {
            await fetchPage()
          } finally {
            setMapLayersLoading((ids) =>
              ids.filter((loader) => loader.loaderId !== _id),
            )
          }
        }
    
        start()
    
        return () => {
          controller.abort('Cleanup')
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
      }, deps)
    

    Image

    This change behavior on key is quite strange and still dont find a way to have proper effect handling - avoid duplicate call of my fetch - consumming much data that needed :/

  9. thejustinwalsh commented on May 2, 2025

    @thejustinwalsh

    The docs describe an effect with an empty dependency array as running on mount and unmount:
    https://react.dev/learn/lifecycle-of-reactive-effects#what-an-effect-with-empty-dependencies-means

    It's a bit surprising to see that in React 19 (in development mode with StrictMode), a component that is re-ordered is treated as if it was unmounted and remounted. This behavior doesn't occur in production, making it unclear if it is intentional.

    In the case where an effect has no dependencies and is used for side-effects on mount, we may have to use patterns that are cautioned against to keep the side-effects consistent between production and development.
    https://react.dev/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development

    I’ve forked the above examples to illustrate this behavior, by adding logging for mount and unmount in the effect:
    React 19: https://stackblitz.com/edit/react-ts-a9ngbghz?file=App.tsx,index.tsx
    React 18: https://stackblitz.com/edit/react-ts-nldaj3yj?file=App.tsx,index.tsx

    I’m hoping to clarify if this behavior will change in future versions of react, or if we should count on it sticking around for a bit?

  10. github-actions commented on Jul 31, 2025

    @github-actions

    This issue has been automatically marked as stale. If this issue is still affecting you, please leave any comment (for example, "bump"), and we'll keep it open. We are sorry that we haven't been able to prioritize it yet. If you have any new additional information, please include it with your comment!

  11. added
    Resolution: Stale
    on Jul 31, 2025
  12. 4 remaining items

  13. krispya commented on Oct 29, 2025

    @krispya
    Author

    Bumping this one more time.

  14. removed
    Resolution: Stale
    on Oct 29, 2025
  15. phb-ig commented on Nov 7, 2025

    @phb-ig

    I spent all day banging my head against this, can confirm. When items are re-ordered in an array, ones that end up in different positions (for some definition of "different positions" that I can't quite figure out) are completely re-mounted (as described in #34307). Here are some code sandboxes that demonstrate with console logging:

    React 19.x - logs mount messages when you click the button: https://codesandbox.io/p/sandbox/i-am-insane-3mzghz
    React 18.x - does not: https://codesandbox.io/p/sandbox/fkqtdg?file=%2Fsrc%2FApp.js

    I have also confirmed in my actual project that this behavior is not present when running the production build (i.e. not strict mode).

  16. github-actions commented on Feb 5, 2026

    @github-actions

    This issue has been automatically marked as stale. If this issue is still affecting you, please leave any comment (for example, "bump"), and we'll keep it open. We are sorry that we haven't been able to prioritize it yet. If you have any new additional information, please include it with your comment!

  17. added
    Resolution: Stale
    on Feb 5, 2026
  18. phb-ig commented on Feb 6, 2026

    @phb-ig

    bump

  19. removed
    Resolution: Stale
    on Feb 6, 2026
  20. rickhanlonii commented on Feb 25, 2026

    @rickhanlonii
    Contributor

    Sorry for the delay - I confirmed this and will look into it.

  21. added and removed
    Status: Unconfirmed
    on Feb 25, 2026
  22. added 3 commits that reference this issue on Feb 26, 2026
    6b9aeac
    9a86561
    a2b2040
  23. sophiebits commented on Jul 7, 2026

    @sophiebits
    Collaborator

    It looks like this is a duplicate of #29585; let's use that issue to track.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions