Skip to content

Changing onViewableItemsChanged on the fly is not supported #30171

Open

Description

@zerocsss

Please provide all the information requested. Issues that do not follow this format are likely to stall.

Description

Changing onViewableItemsChanged on the fly is not supported

React Native version:

0.63.3

Snack, code example, screenshot, or link to a repository:

<FlatList
ref={FlatListRef}
data={data}
inverted={true}
contentContainerStyle={{
flexGrow: 1, justifyContent: 'flex-end',
}}
renderItem={renderItem}
keyExtractor={item => item.id}
viewabilityConfig={{waitForInteraction: true, viewAreaCoveragePercentThreshold: 95}}
onViewableItemsChanged={(info) => {
console.log(info)
}}
/>

image

Activity

  1. isnifer commented on Oct 18, 2020

    @isnifer
    Contributor

    @zerocsss I recommend you to use this technique:
    First of all change property to pass this callback

    -onViewableItemsChanged={...}
    +viewabilityConfigCallbackPairs={viewabilityConfigCallbackPairs.current}

    where viewabilityConfigCallbackPairs is:

    const viewabilityConfigCallbackPairs = useRef([{ viewabilityConfig, onViewableItemsChanged }])

    That's it.

  2. adblanc commented on Nov 12, 2020

    @adblanc

    @zerocsss I recommend you to use this technique:
    First of all change property to pass this callback

    -onViewableItemsChanged={...}
    +viewabilityConfigCallbackPairs={viewabilityConfigCallbackPairs.current}

    where viewabilityConfigCallbackPairs is:

    const viewabilityConfigCallbackPairs = useRef([{ viewabilityConfig, onViewableItemsChanged }])

    That's it.

    Thanks it works like a charm

  3. arbaz-yousuf-jazsoft commented on Dec 23, 2020

    @arbaz-yousuf-jazsoft

    @zerocsss could you please explain it, It didn't work for me

  4. rajeshivn commented on Mar 29, 2021

    @rajeshivn

    @zerocsss could you please explain it, It didn't work for me

    same here not working

  5. Nikolay-Vovk-dataart commented on Apr 9, 2021

    @Nikolay-Vovk-dataart

    you also could wrap it with useCallback if it hasn't any deps (useCallback(() => {...} , []))

  6. johnhaup commented on Apr 16, 2021

    @johnhaup

    @arbaz-yousuf-jazsoft @rajeshivn or anyone still trying to implement the solution above:

    Add this to the top of your functional component:

    const onViewableItemsChanged = ({
      viewableItems,
    }) => {
      // Do stuff
    };
    const viewabilityConfigCallbackPairs = useRef([
      { onViewableItemsChanged },
    ]);

    then render your Flatlist:

    <FlatList
      style={styles.list}
      data={data}
      renderItem={renderItem}
      keyExtractor={(_, index) => `list_item${index}`}
      viewabilityConfigCallbackPairs={
        viewabilityConfigCallbackPairs.current
      }
    />

    Thanks @isnifer this worked great!

  7. omitchen commented on May 12, 2021

    @omitchen
      viewabilityConfigCallbackPairs={
        viewabilityConfigCallbackPairs.current
      }

    This method still has no response in my project. Although no error is reported, onViewableItemsChanged will not be executed.

  8. julienripet commented on Jun 23, 2021

    @julienripet
      viewabilityConfigCallbackPairs={
        viewabilityConfigCallbackPairs.current
      }

    This method still has no response in my project. Although no error is reported, onViewableItemsChanged will not be executed.

    @omitchen I had the same problem, my issue was that I had changed the name of the function onViewableItemsChanged in

    const viewabilityConfigCallbackPairs = useRef([
    { onViewableItemsChanged },
    ]);

    If you want to use a function with a different name, make sure to set it as the onViewableItemsChanged property in the useRef, as follows

    const viewabilityConfigCallbackPairs = useRef([
      { onViewableItemsChanged: MyGreatFunction },
    ]);
  9. sobhanbera commented on Aug 6, 2021

    @sobhanbera

    @zerocsss I recommend you to use this technique:
    First of all change property to pass this callback

    -onViewableItemsChanged={...}
    +viewabilityConfigCallbackPairs={viewabilityConfigCallbackPairs.current}

    where viewabilityConfigCallbackPairs is:

    const viewabilityConfigCallbackPairs = useRef([{ viewabilityConfig, onViewableItemsChanged }])

    That's it.

    This worked for me. Thanks!!

  10. sallarahmed commented on Oct 4, 2021

    @sallarahmed

    Convert component from functional to class and call these methods, this will work like a charm

  11. Qazafi-Dev commented on Nov 24, 2021

    @Qazafi-Dev

    @johnhaup i doing same thing in class component but it giving me error can't find variable onviewablechangeitem but i defined it

  12. Qazafi-Dev commented on Nov 24, 2021

    @Qazafi-Dev

    @sallarahmed can u share class component code? i need it

  13. prasanthvenkatachalam commented on Dec 10, 2021

    @prasanthvenkatachalam

    tried viewabilityConfigCallbackPairs in the function component, But getting Changing onViewableItemsChanged on the fly is not supported Error and Invariant Violation: Changing onViewableItemsChanged on the fly is not supported. Below is my code

    <FlatList
    ref={homeFeedRef}
    showsVerticalScrollIndicator={false}
    ItemSeparatorComponent={FlatListItemSeparator}
    data={
    home.nuggets
    }
    style={{ flex: 1 }}
    
    viewabilityConfigCallbackPairs={[
    {
    viewabilityConfig: {
    itemVisiblePercentThreshold: 100,
    },
    onViewableItemsChanged: handleChangeVIew,
    },
    {
    viewabilityConfig: {
    itemVisiblePercentThreshold: 200,
    },
    onViewableItemsChanged: handleChangeVIew2,
    },
    ]}
    ListHeaderComponent={topSection}
    renderItem={renderItem} />
    

    Also tried the below code, this does not throw any error but function call is not happening. Help needed

    const viewabilityConfigCallbackPairs = useRef([
    { viewabilityConfig, onViewableItemsChanged: handleChangeVIew },
    ]);

  14. abhilakshyadobhal commented on Jun 1, 2022

    @abhilakshyadobhal

    @isnifer tried viewabilityConfigCallbackPairs in the function component, that error got resolved but in the onViewableItemsChanged function I'm using a prop whose value is getting changed but inside the function, I'm not getting that prop new value, it's always giving me the same value which is coming for it the first time

            const indexOfHighlightedProduct = viewableItems.findIndex(({ item }) => item?.styleId === inFocusProduct)
            console.log('inFocusProduct', inFocusProduct)
    
            // if it is currently visible don't animate else animate
            if (indexOfHighlightedProduct > -1) {
                console.log('don"t do something')
            } else {
                console.log('do something')
            }
        }
    

    Here inFocusProduct is the prop whose value is getting but it's not showing the changed value

  15. 22 remaining items

  16. AnandKuhar1100 commented on Jul 16, 2023

    @AnandKuhar1100

    If we are using onViewableItemsChanged with useRef or useCallback then we are not getting updated redux values directly in onViewableItemsChanged. We need to use useRef with redux values as well. Is there any other approach for the same?

    • If we pass any dependency in useCallback (with onViewableItemsChanged) then it gives same error Changing onViewableItemsChanged on the fly is not supported
  17. KhineKhineMyatNoe commented on Aug 23, 2023

    @KhineKhineMyatNoe

    this one works for react native 0.71.1

  18. SirCameron commented on Oct 6, 2023

    @SirCameron

    I'm not sure what the point of having a functioned defined in stone (useRef, useCallback with []) to receive the viewable item updates when it can't DO anything with that information - cannot update state or anything like that... it's pointless.

  19. nguyentrancong commented on Jan 1, 2024

    @nguyentrancong

    I've fixed it, and working with me,
    You see code belw

    ` const viewConfigRef = React.useRef({viewAreaCoveragePercentThreshold: 50});

    const onViewCallBack = React.useCallback(async (info: any) => {
    const item = await head(info?.viewableItems);
    onChangePosition(item.index);
    }, []);

    return (
    <FlatList
    ref={flatListRef}
    data={questions}
    keyExtractor={item => item.id}
    renderItem={renderItemQuestion}
    style={styles.flatList}
    pagingEnabled
    horizontal
    showsHorizontalScrollIndicator={false}
    viewabilityConfig={viewConfigRef.current}
    onViewableItemsChanged={onViewCallBack}
    />
    );`

  20. added
    Resolution: Backlog
    Tech: React Native Core
    and removed on Mar 14, 2024
  21. gaearon commented on Mar 14, 2024

    @gaearon
    Collaborator

    I tagged this as a bug but not sure when the RN team will be able to dedicate time to it.

    In the meantime, a workaround like this should work:

    import {useCallback, useInsertionEffect, useRef} from 'react'
    
    function MyComponent() {
      const onViewableItemsChanged = useNonReactiveCallback(() => {
        // ... your code ...
      });
      
      <FlatList
        onViewableItemsChanged={onViewableItemsChanged}
        // ...
      />
    }
    
    // Note: Use this sparingly.
    function useNonReactiveCallback<T extends Function>(fn: T): T {
      const ref = useRef(fn)
      useInsertionEffect(() => {
        ref.current = fn
      }, [fn])
      return useCallback(
        (...args: any) => {
          const latestFn = ref.current
          return latestFn(...args)
        },
        [ref],
      ) as unknown as T
    }
  22. NickGerleman commented on Mar 14, 2024

    @NickGerleman
    Contributor

    RN 0.73 makes this a bit better: 5cfa125

  23. added
    Never gets stale
    on Mar 14, 2024
  24. imfunniee commented on Mar 18, 2024

    @imfunniee

    hopefully the new architecture solves this

  25. Frankcaozas commented on Apr 27, 2025

    @Frankcaozas

    I tagged this as a bug but not sure when the RN team will be able to dedicate time to it.

    In the meantime, a workaround like this should work:

    import {useCallback, useInsertionEffect, useRef} from 'react'

    function MyComponent() {
    const onViewableItemsChanged = useNonReactiveCallback(() => {
    // ... your code ...
    });

    <FlatList
    onViewableItemsChanged={onViewableItemsChanged}
    // ...
    />
    }

    // Note: Use this sparingly.
    function useNonReactiveCallback(fn: T): T {
    const ref = useRef(fn)
    useInsertionEffect(() => {
    ref.current = fn
    }, [fn])
    return useCallback(
    (...args: any) => {
    const latestFn = ref.current
    return latestFn(...args)
    },
    [ref],
    ) as unknown as T
    }

    I tagged this as a bug but not sure when the RN team will be able to dedicate time to it.

    In the meantime, a workaround like this should work:

    import {useCallback, useInsertionEffect, useRef} from 'react'

    function MyComponent() {
    const onViewableItemsChanged = useNonReactiveCallback(() => {
    // ... your code ...
    });

    <FlatList
    onViewableItemsChanged={onViewableItemsChanged}
    // ...
    />
    }

    // Note: Use this sparingly.
    function useNonReactiveCallback(fn: T): T {
    const ref = useRef(fn)
    useInsertionEffect(() => {
    ref.current = fn
    }, [fn])
    return useCallback(
    (...args: any) => {
    const latestFn = ref.current
    return latestFn(...args)
    },
    [ref],
    ) as unknown as T
    }

    if i am using react 16, can i replace useInsertionEffect with useLayoutEffect

  26. mchaptel commented on Feb 28, 2026

    @mchaptel

    Depending on what you need to update in your onViewableItemsChanged, it is possible to create some useState to track the index, then a useEffect with that index as dependency. This effect will have access to the whole scope of the functional component and be able to make any change and read fresh values.

    ex:

    const myComponent = ()=>{
      const [items, setItems] = useState();
      useEffect(()=>{
        // execute some code when items change wich involves reading/changing component state
      }, [items])
    
      const updateItems=useCallback(({ViewableItems})=>{
        setItems(ViewableItems); 
      }, []) // lack of dependencies will avoid triggering the error
    
      return (
        <Flatlist
           onViewableItemsChanged={updateItems}
          ...
         /> 
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugComponent: FlatListNever gets staleResolution: BacklogTech: React Native Core

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions