Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply lazy loading in flatlist in react native

Tags:

What is the best possible way to apply lazy load in Flatlist in react native. Currently there is infinite scroll in the flatlist. I am new to React native so i dont have any idea.

like image 584
elle kay Avatar asked Apr 04 '18 10:04

elle kay


People also ask

Is FlatList lazy loading?

Flatlist supports lazy loading, Flatlist provide on scroll pagination, Flatlist avoid unnecessary rerendering, Flatlist scrolls are fast and page rendering time decreases once used.

Can we use react lazy in React Native?

Even though React. lazy is supposed to be used with dynamic imports, it supports just about any Promise that resolves to a react component. This fits perfectly with our needs.


1 Answers

You should use

<FlatList ....
onEndReached={this.endReached}
onEndReachedThreshold={.7}
.../>

the onEndReached: Called once when the scroll position gets within onEndReachedThreshold of the rendered content.

and onEndReachedThreshold: How far from the end (in units of visible length of the list) the bottom edge of the list must be from the end of the content to trigger the onEndReached callback. Thus a value of 0.5 will trigger onEndReached when the end of the content is within half the visible length of the list.

E.g:

class YourClass extends Component {
  state = { list: [], offset: 0, limit: 100 };
  componentDidMount() {
      this.fetchResult();
  }
    fetchResult = () => {
        const { offset, limit, list } = this.state;
        fetchModeDateFromAPI(offset, limit).then(res => {
        if (!res.list) return;
        this.setState({
            list: list.concat(res.list),
            offset: offset + 100,
            limit: limit
        });
        });
    };
    render = () => {
        return (
        <FlatList
            style={{ flex: 1 }}
            extraData={this.state}
            onEndReached={this.fetchResult}
            onEndReachedThreshold={0.7}
            data={this.state.list}
            renderItem={rowData => {}}
            keyExtractor={item => item.id.toString()}
        />
        );
    };
}
like image 59
Deivison Sporteman Avatar answered Sep 18 '22 11:09

Deivison Sporteman