Skip to content

Stale closure with useAnimatedScrollHandler when passed to memo() #5364

Closed

Description

@gaearon

Description

In idiomatic React, it is presumed that it is safe to skip re-rendering if all props are referentially the same. Built-in optimizations like memo rely on that, and the upcoming React compiler will rely on that even stronger.

It seems like useAnimatedScrollHandler breaks this constraint. I haven't looked at how it works, but it seems like it retains referential identity but relies on re-rendering to swap out its callback. This leads to non-deterministic behavior — add memo() anywhere in the middle of the path of onScroll being passed down, and the callback will have a stale closure.

This probably points to breaking the rules of React (e.g. mutation in render).

Steps to reproduce

Code:

import * as React from 'react'
import {View} from 'react-native'
import Animated, {useAnimatedScrollHandler} from 'react-native-reanimated'

export default function App() {
  const [x, setX] = React.useState(0)
  React.useEffect(() => {
    let id = setInterval(() => setX(x => x + 1), 1000)
    return () => clearInterval(id)
  }, [])

  const handler = useAnimatedScrollHandler({
    onScroll() {
      console.log(x)
    },
  })

  return <Child onScroll={handler} />
}

const Child = React.memo(function ({onScroll}) {
  return (
    <View style={{flex: 1, flexDirection: 'row'}}>
      <Animated.FlatList
        onScroll={onScroll}
        style={{flex: 1, backgroundColor: 'red'}}
        contentContainerStyle={{
          paddingTop: 1000,
        }}
      />
    </View>
  )
})

Note the x never updates.

Then remove React.memo around Child.

Now x updates.

Runnable demo

git clone https://github.com/bluesky-social/social-app.git
cd social-app

git checkout reanimated-stuck-onscroll-repro-memo
yarn
yarn start --clear

The repro is in App.native.tsx.

This definitely reproes on iOS and Android. Haven't checked web.

Snack or a link to a repository

https://github.com/bluesky-social/social-app/tree/reanimated-stuck-onscroll-repro-memo

Reanimated version

3.4.3

React Native version

0.72.5

Platforms

Android, iOS

JavaScript runtime

Hermes

Workflow

None

Architecture

Paper (Old Architecture)

Build type

None

Device

None

Device model

No response

Acknowledgements

Yes

Activity

  1. github-actions commented on Nov 10, 2023

    @github-actions

    Hey! 👋

    The issue doesn't seem to contain a minimal reproduction.

    Could you provide a snack or a link to a GitHub repository under your username that reproduces the problem?

  2. gaearon commented on Nov 10, 2023

    @gaearon
    ContributorAuthor

    It does provide a repro, but the repro is not under my username. This seems like an odd policy for a bot — it is quite common to work on not personal projects :)

  3. self-assigned this
    on Dec 17, 2023
  4. tjzel commented on Dec 17, 2023

    @tjzel
    Collaborator

    Hi @gaearon, you are right - useAnimatedScrollHandler and every other handler that is an instance of WorkletEventHandler is reattached during the render of a given component. Therefore, with no re-renders, there's never a call to the UI thread to attach the new worklet instead.

    I'm really thankful for this issue (your issues in general). You are pointing to various places of Reanimated that could be done better ❤️

    I will consult this with the team to change this behavior in the future.

  5. gaearon commented on Feb 23, 2024

    @gaearon
    ContributorAuthor

    Is there an issue where I could track this? I think it’s really important that this is tracked.

    As an example, this makes Reanimated a blocker for teams wanting to adopt the React Compiler when it ships.

  6. kmagiera commented on Feb 26, 2024

    @kmagiera
    Member

    thanks for rising this issue. From talking with @tjzel it appears like this issue got closed by accident along with #5345. However, the latter shouldn't also be closed because there was no fix implemented there but rather @tjzel only expressed that passing result of useAnimatedScroll hook to multiple components isn't supported. In that instance of the problem, it may require more time for us to implement the fix, but I also understand that this other issue isn't as pressing in terms of compiler compatibility. For the time being we will likely add an error message when someone attempts to use one scroll callback in more than one component (will add more context in #5345 about that).

    As for this particular issue, I'm going to reopen it. We now understand what the underlying problem was and @tjzel will work on a fix. As pointed out, the issue was due to a misuse of useRef that make this hook always return the same object while some fields of the object are being mutated inside the hook. We identified several other places in the codebase where similar pattern was used and for that we will create a new issue to track problem of fixing it in other places.

  7. added a commit that references this issue on Mar 6, 2024
    89f76a7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Needs reviewIssue is ready to be reviewed by a maintainerPlatform: AndroidThis issue is specific to AndroidPlatform: iOSThis issue is specific to iOS

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions