Skip to content

Conversation

MatiPl01
Copy link
Member

@MatiPl01 MatiPl01 commented Jun 2, 2025

Summary

This PR fixes useScrollViewOffset hook not updating the returned SharedValue if the scrollable to which the ref is attached is rendered with some delay.

The previous implementation didn't work because the animatedRef was uninitialized when the useEffect hook in the useScrollViewOffset was called if the ref wasn't passed to any component. The useEffect was not triggered after the ref was passed to the component later on, even though (at least as I understand) the animatedRef?.current in the useEffect dependencies changed, because this change happened after hook dependencies were recalculated.

Since the code od the component executes from the top to the bottom during render, the useEffect hook dependencies array was created before the animatedRef.current was set in the function created within the useAnimatedRef hook (it is set as soon as the ref function is called with the exiting component argument, which happened after useEffect hook dependencies were recalculated).

Example recordings

Mobile

Before After
Screen.Recording.2025-06-02.at.18.30.20.mp4
Screen.Recording.2025-06-02.at.18.29.37.mp4

Web

Before After
Screen.Recording.2025-06-02.at.18.31.53.mp4
Screen.Recording.2025-06-02.at.18.33.03.mp4

Test plan

Copy-paste the following code snippet and see how it works.

Code snippet
import React, { useState } from 'react';
import { Button, ScrollView, StyleSheet, Text, View } from 'react-native';
import type Animated from 'react-native-reanimated';
import {
  useAnimatedReaction,
  useAnimatedRef,
  useScrollViewOffset,
} from 'react-native-reanimated';

export default function EmptyExample() {
  const [shouldRender, setShouldRender] = useState(false);
  const scrollRef = useAnimatedRef<Animated.ScrollView>();
  const scrollOffset = useScrollViewOffset(scrollRef);

  useAnimatedReaction(
    () => scrollOffset.value,
    (value) => {
      console.log('scrollOffset', value);
    }
  );

  return (
    <View style={styles.container}>
      <Text style={styles.text}>
        ScrollView is {shouldRender ? 'rendered' : 'not rendered'}
      </Text>
      <Button
        title={shouldRender ? 'Remove ScrollView' : 'Render ScrollView'}
        onPress={() => setShouldRender(!shouldRender)}
      />

      {shouldRender && (
        <ScrollView
          ref={scrollRef}
          scrollEventThrottle={1000 / 60}
          style={styles.scrollView}>
          {Array.from({ length: 20 }).map((_, index) => (
            <View key={index} style={styles.item}>
              <Text style={styles.itemText}>Scroll Item {index + 1}</Text>
            </View>
          ))}
        </ScrollView>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    padding: 20,
  },
  text: {
    fontSize: 16,
    marginBottom: 10,
  },
  scrollView: {
    flex: 1,
    marginTop: 20,
  },
  item: {
    height: 100,
    backgroundColor: '#f0f0f0',
    marginVertical: 8,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  itemText: {
    fontSize: 16,
    color: '#333',
  },
});

I also checked if the following examples in the example app still work (on mobile and web):

  • useAnimatedScrollHandler
  • scrollTo
  • useScrollViewOffset

@MatiPl01 MatiPl01 self-assigned this Jun 2, 2025
@MatiPl01 MatiPl01 marked this pull request as ready for review June 2, 2025 16:38
@MatiPl01 MatiPl01 requested review from tjzel, tomekzaw and patrycjakalinska and removed request for tomekzaw June 2, 2025 16:38
@MatiPl01 MatiPl01 changed the title @matipl01/fix use scroll view offset for delayed ref initialization fix: useScrollViewOffset not working after delayed ref initialization Jun 2, 2025
Copy link
Contributor

@patrycjakalinska patrycjakalinska left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've tested it and it works okay so I'm going with approve. However I'd feel safer with merge after @tjzel approval as this refactor is not neccessarily in my field 🪨

@MatiPl01 MatiPl01 requested a review from tjzel June 3, 2025 14:02
@MatiPl01 MatiPl01 added this pull request to the merge queue Jun 4, 2025
Merged via the queue into main with commit b9b83d8 Jun 4, 2025
10 checks passed
@MatiPl01 MatiPl01 deleted the @matipl01/fix-useScrollViewOffset-for-delayed-ref-initialization branch June 4, 2025 14:03
github-merge-queue bot pushed a commit that referenced this pull request Jun 4, 2025
## Summary

This PR removes duplicate code between the web and the native
implementation of the `useAnimatedRef` hook as asked in
#7612 (comment)

## Test plan

Copy-paste the following code snippet and see how it works.

<details>
<summary>Code snippet</summary>

```tsx
import React, { useState } from 'react';
import { Button, ScrollView, StyleSheet, Text, View } from 'react-native';
import type Animated from 'react-native-reanimated';
import {
  useAnimatedReaction,
  useAnimatedRef,
  useScrollViewOffset,
} from 'react-native-reanimated';

export default function EmptyExample() {
  const [shouldRender, setShouldRender] = useState(false);
  const scrollRef = useAnimatedRef<Animated.ScrollView>();
  const scrollOffset = useScrollViewOffset(scrollRef);

  useAnimatedReaction(
    () => scrollOffset.value,
    (value) => {
      console.log('scrollOffset', value);
    }
  );

  return (
    <View style={styles.container}>
      <Text style={styles.text}>
        ScrollView is {shouldRender ? 'rendered' : 'not rendered'}
      </Text>
      <Button
        title={shouldRender ? 'Remove ScrollView' : 'Render ScrollView'}
        onPress={() => setShouldRender(!shouldRender)}
      />

      {shouldRender && (
        <ScrollView
          ref={scrollRef}
          scrollEventThrottle={1000 / 60}
          style={styles.scrollView}>
          {Array.from({ length: 20 }).map((_, index) => (
            <View key={index} style={styles.item}>
              <Text style={styles.itemText}>Scroll Item {index + 1}</Text>
            </View>
          ))}
        </ScrollView>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    padding: 20,
  },
  text: {
    fontSize: 16,
    marginBottom: 10,
  },
  scrollView: {
    flex: 1,
    marginTop: 20,
  },
  item: {
    height: 100,
    backgroundColor: '#f0f0f0',
    marginVertical: 8,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  itemText: {
    fontSize: 16,
    color: '#333',
  },
});
```
</details>
MatiPl01 added a commit that referenced this pull request Jun 26, 2025
…#7612)

This PR fixes `useScrollViewOffset` hook not updating the returned
SharedValue if the scrollable to which the ref is attached is rendered
with some delay.

The previous implementation didn't work because the `animatedRef` was
uninitialized when the `useEffect` hook in the `useScrollViewOffset` was
called if the ref wasn't passed to any component. The `useEffect` was
not triggered after the ref was passed to the component later on, even
though (at least as I understand) the `animatedRef?.current` in the
`useEffect` dependencies changed, because this change happened after
hook dependencies were recalculated.

Since the code od the component executes from the top to the bottom
during render, the `useEffect` hook dependencies array was created
before the `animatedRef.current` was set in the function created within
the `useAnimatedRef` hook (it is set as soon as the ref function is
called with the exiting component argument, which happened after
`useEffect` hook dependencies were recalculated).

| Before | After |
|-|-|
| <video
src="https://github.com/user-attachments/assets/16b2d7dd-ec29-45be-ab7e-44007e922204"
/> | <video
src="https://github.com/user-attachments/assets/9e6f4475-4f66-4b46-a42b-2322a3cdb301"
/> |

| Before | After |
|-|-|
| <video
src="https://github.com/user-attachments/assets/4e8f02af-5aee-498a-a738-a674db062bbc"
/> | <video
src="https://github.com/user-attachments/assets/cd0965da-7e2c-4281-ac3b-f3f58c97e153"
/> |

Copy-paste the following code snippet and see how it works.

<details>
<summary>Code snippet</summary>

```tsx
import React, { useState } from 'react';
import { Button, ScrollView, StyleSheet, Text, View } from 'react-native';
import type Animated from 'react-native-reanimated';
import {
  useAnimatedReaction,
  useAnimatedRef,
  useScrollViewOffset,
} from 'react-native-reanimated';

export default function EmptyExample() {
  const [shouldRender, setShouldRender] = useState(false);
  const scrollRef = useAnimatedRef<Animated.ScrollView>();
  const scrollOffset = useScrollViewOffset(scrollRef);

  useAnimatedReaction(
    () => scrollOffset.value,
    (value) => {
      console.log('scrollOffset', value);
    }
  );

  return (
    <View style={styles.container}>
      <Text style={styles.text}>
        ScrollView is {shouldRender ? 'rendered' : 'not rendered'}
      </Text>
      <Button
        title={shouldRender ? 'Remove ScrollView' : 'Render ScrollView'}
        onPress={() => setShouldRender(!shouldRender)}
      />

      {shouldRender && (
        <ScrollView
          ref={scrollRef}
          scrollEventThrottle={1000 / 60}
          style={styles.scrollView}>
          {Array.from({ length: 20 }).map((_, index) => (
            <View key={index} style={styles.item}>
              <Text style={styles.itemText}>Scroll Item {index + 1}</Text>
            </View>
          ))}
        </ScrollView>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    padding: 20,
  },
  text: {
    fontSize: 16,
    marginBottom: 10,
  },
  scrollView: {
    flex: 1,
    marginTop: 20,
  },
  item: {
    height: 100,
    backgroundColor: '#f0f0f0',
    marginVertical: 8,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  itemText: {
    fontSize: 16,
    color: '#333',
  },
});
```
</details>

I also checked if the following examples in the example app still work
(on mobile and web):

- useAnimatedScrollHandler
- scrollTo
- useScrollViewOffset
MatiPl01 added a commit that referenced this pull request Jun 26, 2025
…initialization (#7704)

Chery-pick of #7612 with some necessary adjustments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants