প্রতিক্রিয়া সঙ্গে বড় তালিকা কর্মক্ষমতা


86

আমি প্রতিক্রিয়া সহ ফিল্টারযোগ্য তালিকা বাস্তবায়নের প্রক্রিয়াধীন। নীচের চিত্রে তালিকার কাঠামোটি দেখানো হয়েছে।

এখানে চিত্র বর্ণনা লিখুন

প্রাকদর্শন করুন

এটি কীভাবে কাজ করবে বলে বর্ণনা করা হচ্ছে:

  • রাষ্ট্রটি সর্বোচ্চ স্তরের উপাদান, Searchউপাদানটিতে থাকে।
  • রাষ্ট্রটি নীচে বর্ণিত:
{
    দৃশ্যমান: বুলিয়ান,
    ফাইল: অ্যারে,
    ফিল্টারড: অ্যারে,
    ক্যোরি: স্ট্রিং,
    বর্তমানে সিলেক্ট ইন্ডেক্স: পূর্ণসংখ্যা
}
  • files সম্ভাব্যভাবে খুব বড়, অ্যারে ফাইল ফাইলগুলি রয়েছে (10000 এন্ট্রি একটি প্রশংসনীয় সংখ্যা)।
  • filteredব্যবহারকারী কমপক্ষে 2 টি অক্ষর টাইপ করার পরে ফিল্টার করা অ্যারে হয়। আমি জানি এটি ডেরাইভেটিভ ডেটা এবং রাজ্যে এটি সংরক্ষণ করার বিষয়ে যেমন একটি যুক্তি তৈরি করা যেতে পারে তবে এটির জন্য এটি প্রয়োজন
  • currentlySelectedIndex ফিল্টারড তালিকা থেকে বর্তমানে নির্বাচিত উপাদানগুলির সূচক যা।

  • ব্যবহারকারীর Inputউপাদানগুলিতে 2 টিরও বেশি বর্ণ রয়েছে , অ্যারে ফিল্টার করা হয় এবং ফিল্টার করা অ্যারেতে প্রতিটি প্রবেশের জন্য একটি Resultউপাদান রেন্ডার করা হয়

  • প্রতিটি Resultউপাদান পুরো পথটি প্রদর্শন করছে যা কোয়েরির সাথে আংশিক মিল রয়েছে এবং পথটির আংশিক মিলের অংশটি হাইলাইট করা হয়েছে। উদাহরণস্বরূপ কোনও ফলাফলের ডিওএম, ব্যবহারকারী যদি 'লে' টাইপ করেন তবে এটি এমন কিছু হতে পারে:

    <li>this/is/a/fi<strong>le</strong>/path</li>

  • Inputউপাদানটি অ্যারের currentlySelectedIndexউপর ভিত্তি করে পরিবর্তনগুলিকে কেন্দ্র করে যখন ব্যবহারকারী উপরে বা নীচে কীগুলি filteredটিপান। এটি Resultসূচকটির সাথে মেলে এমন উপাদানটিকে পুনরায় রেন্ডার করায় নির্বাচিত হিসাবে চিহ্নিত হিসাবে চিহ্নিত করে

সমস্যা

প্রাথমিকভাবে আমি filesপ্রতিক্রিয়াটির বিকাশের সংস্করণটি ব্যবহার করে একটি ছোট্ট যথেষ্ট পরিমাণে অ্যারে দিয়ে এটি পরীক্ষা করেছি এবং সব ঠিকঠাক কাজ করেছে।

সমস্যাটি উপস্থিত হয়েছিল যখন আমাকে files10000 এন্ট্রি হিসাবে বড় অ্যারের সাথে ডিল করতে হয়েছিল । ইনপুটটিতে 2 টি অক্ষর টাইপ করা একটি বড় তালিকা তৈরি করবে এবং যখন আমি নেভিগেট করতে উপরে এবং ডাউন কী টিপতাম তখন এটি খুব পিছিয়ে থাকবে।

প্রথমে আমার কাছে উপাদানগুলির জন্য একটি সংজ্ঞায়িত উপাদান Resultছিল না এবং আমি কেবলমাত্র Searchউপাদানটির প্রতিটি রেন্ডারে ফ্লাইতে তালিকা তৈরি করছিলাম , যেমন:

results  = this.state.filtered.map(function(file, index) {
    var start, end, matchIndex, match = this.state.query;

     matchIndex = file.indexOf(match);
     start = file.slice(0, matchIndex);
     end = file.slice(matchIndex + match.length);

     return (
         <li onClick={this.handleListClick}
             data-path={file}
             className={(index === this.state.currentlySelected) ? "valid selected" : "valid"}
             key={file} >
             {start}
             <span className="marked">{match}</span>
             {end}
         </li>
     );
}.bind(this));

আপনি বলতে পারেন যে যতবার currentlySelectedIndexপরিবর্তন হয়েছে, এটি পুনরায় রেন্ডার করবে এবং প্রতিবার তালিকাটি পুনরায় তৈরি করা হবে। আমি ভেবেছিলাম যেহেতু আমি keyপ্রতিটি liউপাদানটির জন্য একটি মান নির্ধারণ করেছি প্রতিক্রিয়াটি অন্য liযে কোনও উপাদানগুলির classNameপরিবর্তন ঘটে নি তার পুনরায় রেন্ডারিং এড়াতে পারবে , তবে দৃশ্যত এটি এমনটি ছিল না।

আমি Resultউপাদানগুলির জন্য একটি শ্রেণি সংজ্ঞায়িত করে শেষ করেছি , যেখানে এটি স্পষ্ট করে যাচাই করে যে প্রতিটি Resultউপাদান পূর্বে নির্বাচিত হয়েছিল এবং বর্তমান ব্যবহারকারীর ইনপুটের উপর ভিত্তি করে পুনরায় রেন্ডার করা উচিত কিনা:

var ResultItem = React.createClass({
    shouldComponentUpdate : function(nextProps) {
        if (nextProps.match !== this.props.match) {
            return true;
        } else {
            return (nextProps.selected !== this.props.selected);
        }
    },
    render : function() {
        return (
            <li onClick={this.props.handleListClick}
                data-path={this.props.file}
                className={
                    (this.props.selected) ? "valid selected" : "valid"
                }
                key={this.props.file} >
                {this.props.children}
            </li>
        );
    }
});

এবং তালিকাটি এখন যেমন তৈরি করা হয়েছে:

results = this.state.filtered.map(function(file, index) {
    var start, end, matchIndex, match = this.state.query, selected;

    matchIndex = file.indexOf(match);
    start = file.slice(0, matchIndex);
    end = file.slice(matchIndex + match.length);
    selected = (index === this.state.currentlySelected) ? true : false

    return (
        <ResultItem handleClick={this.handleListClick}
            data-path={file}
            selected={selected}
            key={file}
            match={match} >
            {start}
            <span className="marked">{match}</span>
            {end}
        </ResultItem>
    );
}.bind(this));
}

This made performance slightly better, but it's still not good enough. Thing is when I tested on the production version of React things worked buttery smooth, no lag at all.

BOTTOMLINE

Is such a noticeable discrepancy between development and production versions of React normal?

Am I understanding/doing something wrong when I think about how React manages the list?

UPDATE 14-11-2016

I have found this presentation of Michael Jackson, where he tackles an issue very similar to this one: https://youtu.be/7S8v8jfLb1Q?t=26m2s

The solution is very similar to the one proposed by AskarovBeknar's answer, below

UPDATE 14-4-2018

Since this is apparently a popular question and things have progressed since the original question was asked, while I do encourage you to watch the video linked above, in order to get a grasp of a virtual layout, I also encourage you to use the React Virtualized library if you do not want to re-invent the wheel.


What do you mean by development/production version of react?
Dibesjr


Ah I see, thanks. So to answer one of your questions, it says there is a discrepancy in optimization between the versions. One thing to watch out for in big lists is creating functions in your render. It will have a performance hit when you get into giant lists. I would try and see how long it takes to generate that list using their perf tools facebook.github.io/react/docs/perf.html
Dibesjr

2
I think you should reconsidering using Redux because it's exactly what you need here (or any kind of flux implementation). You should definitively take a look at this presentation : Big List High Performance React & Redux
Pierre Criulanscy

2
I doubt that a user has any benefit of scrolling through 10000 results. So what if you only render the top-100 results or so, and update these based on the query.
Koen.

উত্তর:


18

As with many of the other answers to this question the main problem lies in the fact that rendering so many elements in the DOM whilst doing filtering and handling key events is going to be slow.

You are not doing anything inherently wrong with regards to React that is causing the issue but like many of the issues that are performance related the UI can also take a big percentage of the blame.

If your UI is not designed with efficiency in mind even tools like React that are designed to be performant will suffer.

Filtering the result set is a great start as mentioned by @Koen

I've played around with the idea a bit and created an example app illustrating how I might start to tackle this kind of problem.

This is by no means production ready code but it does illustrate the concept adequately and can be modified to be more robust, feel free to take a look at the code - I hope at the very least it gives you some ideas...;)

react-large-list-example

enter image description here


1
I really feel bad for having to choose just one answer, they all seem to have effort put in them, but I am currently on vacation with no PC and cannot really check them out with the attention they deserve. I chose this one because it is short enough and to the point, to understand even when reading from a phone. Lame reason I know.
Dimitris Karagiannis

What do you mean by edit host file 127.0.0.1 * http://localhost:3001?
stackjlei

@stackjlei I think he meant mapping 127.0.0.1 to localhost:3001 in /etc/hosts
Maverick

16

My experience with a very similar problem is that react really suffers if there are more than 100-200 or so components in the DOM at once. Even if you are super careful (by setting up all your keys and/or implementing a shouldComponentUpdate method) to only to change one or two components on a re-render, you're still going to be in a world of hurt.

The slow part of react at the moment is when it compares the difference between the virtual DOM and the real DOM. If you have thousands of components but only update a couple, it doesn't matter, react still has a massive difference operation to do between the DOMs.

When I write pages now I try to design them to minimise the number of components, one way to do this when rendering large lists of components is to... well... not render large lists of components.

What I mean is: only render the components you can currently see, render more as you scroll down, you're user isn't likely to scroll down through thousands of components any way.... I hope.

A great library for doing this is:

https://www.npmjs.com/package/react-infinite-scroll

With a great how-to here:

http://www.reactexamples.com/react-infinite-scroll/

I'm afraid it doesn't remove components that are off the top of the page though, so if you scroll for long enough you're performance issues will start to reemerge.

I know it isn't good practice to provide a link as answer, but the examples they provide are going to explain how to use this library much better than I can here. Hopefully I have explained why big lists are bad, but also a work around.


2
Update: the package that is in this answer is not maintained. A fork is setup on npmjs.com/package/react-infinite-scroller
Ali Al Amine

11

First of all, the difference between the development and production version of React is huge because in production there are many bypassed sanity checks (such as prop types verification).

Then, I think you should reconsider using Redux because it would be extremely helpful here for what you need (or any kind of flux implementation). You should definitively take a look at this presentation : Big List High Performance React & Redux.

But before diving into redux, you need to made some ajustements to your React code by splitting your components into smaller components because shouldComponentUpdate will totally bypass the rendering of children, so it's a huge gain.

When you have more granular components, you can handle the state with redux and react-redux to better organize the data flow.

I was recently facing a similar issue when I needed to render one thousand rows and be able to modify each row by editing its content. This mini app displays a list of concerts with potential duplicates concerts and I need to chose for each potential duplicate if I want to mark the potential duplicate as an original concert (not a duplicate) by checking the checkbox, and, if necessary, edit the name of the concert. If I do nothing for a particular potential duplicate item, it will be considered duplicate and will be deleted.

Here is what it looks like :

enter image description here

There are basically 4 mains components (there is only one row here but it's for the sake of the example) :

enter image description here

Here is the full code (working CodePen : Huge List with React & Redux) using redux, react-redux, immutable, reselect and recompose:

const initialState = Immutable.fromJS({ /* See codepen, this is a HUGE list */ })

const types = {
    CONCERTS_DEDUP_NAME_CHANGED: 'diggger/concertsDeduplication/CONCERTS_DEDUP_NAME_CHANGED',
    CONCERTS_DEDUP_CONCERT_TOGGLED: 'diggger/concertsDeduplication/CONCERTS_DEDUP_CONCERT_TOGGLED',
};

const changeName = (pk, name) => ({
    type: types.CONCERTS_DEDUP_NAME_CHANGED,
    pk,
    name
});

const toggleConcert = (pk, toggled) => ({
    type: types.CONCERTS_DEDUP_CONCERT_TOGGLED,
    pk,
    toggled
});


const reducer = (state = initialState, action = {}) => {
    switch (action.type) {
        case types.CONCERTS_DEDUP_NAME_CHANGED:
            return state
                .updateIn(['names', String(action.pk)], () => action.name)
                .set('_state', 'not_saved');
        case types.CONCERTS_DEDUP_CONCERT_TOGGLED:
            return state
                .updateIn(['concerts', String(action.pk)], () => action.toggled)
                .set('_state', 'not_saved');
        default:
            return state;
    }
};

/* configureStore */
const store = Redux.createStore(
    reducer,
    initialState
);

/* SELECTORS */

const getDuplicatesGroups = (state) => state.get('duplicatesGroups');

const getDuplicateGroup = (state, name) => state.getIn(['duplicatesGroups', name]);

const getConcerts = (state) => state.get('concerts');

const getNames = (state) => state.get('names');

const getConcertName = (state, pk) => getNames(state).get(String(pk));

const isConcertOriginal = (state, pk) => getConcerts(state).get(String(pk));

const getGroupNames = reselect.createSelector(
    getDuplicatesGroups,
    (duplicates) => duplicates.flip().toList()
);

const makeGetConcertName = () => reselect.createSelector(
    getConcertName,
    (name) => name
);

const makeIsConcertOriginal = () => reselect.createSelector(
    isConcertOriginal,
    (original) => original
);

const makeGetDuplicateGroup = () => reselect.createSelector(
    getDuplicateGroup,
    (duplicates) => duplicates
);



/* COMPONENTS */

const DuplicatessTableRow = Recompose.onlyUpdateForKeys(['name'])(({ name }) => {
    return (
        <tr>
            <td>{name}</td>
            <DuplicatesRowColumn name={name}/>
        </tr>
    )
});

const PureToggle = Recompose.onlyUpdateForKeys(['toggled'])(({ toggled, ...otherProps }) => (
    <input type="checkbox" defaultChecked={toggled} {...otherProps}/>
));


/* CONTAINERS */

let DuplicatesTable = ({ groups }) => {

    return (
        <div>
            <table className="pure-table pure-table-bordered">
                <thead>
                    <tr>
                        <th>{'Concert'}</th>
                        <th>{'Duplicates'}</th>
                    </tr>
                </thead>
                <tbody>
                    {groups.map(name => (
                        <DuplicatesTableRow key={name} name={name} />
                    ))}
                </tbody>
            </table>
        </div>
    )

};

DuplicatesTable.propTypes = {
    groups: React.PropTypes.instanceOf(Immutable.List),
};

DuplicatesTable = ReactRedux.connect(
    (state) => ({
        groups: getGroupNames(state),
    })
)(DuplicatesTable);


let DuplicatesRowColumn = ({ duplicates }) => (
    <td>
        <ul>
            {duplicates.map(d => (
                <DuplicateItem
                    key={d}
                    pk={d}/>
            ))}
        </ul>
    </td>
);

DuplicatessRowColumn.propTypes = {
    duplicates: React.PropTypes.arrayOf(
        React.PropTypes.string
    )
};

const makeMapStateToProps1 = (_, { name }) => {
    const getDuplicateGroup = makeGetDuplicateGroup();
    return (state) => ({
        duplicates: getDuplicateGroup(state, name)
    });
};

DuplicatesRowColumn = ReactRedux.connect(makeMapStateToProps1)(DuplicatesRowColumn);


let DuplicateItem = ({ pk, name, toggled, onToggle, onNameChange }) => {
    return (
        <li>
            <table>
                <tbody>
                    <tr>
                        <td>{ toggled ? <input type="text" value={name} onChange={(e) => onNameChange(pk, e.target.value)}/> : name }</td>
                        <td>
                            <PureToggle toggled={toggled} onChange={(e) => onToggle(pk, e.target.checked)}/>
                        </td>
                    </tr>
                </tbody>
            </table>
        </li>
    )
}

const makeMapStateToProps2 = (_, { pk }) => {
    const getConcertName = makeGetConcertName();
    const isConcertOriginal = makeIsConcertOriginal();

    return (state) => ({
        name: getConcertName(state, pk),
        toggled: isConcertOriginal(state, pk)
    });
};

DuplicateItem = ReactRedux.connect(
    makeMapStateToProps2,
    (dispatch) => ({
        onNameChange(pk, name) {
            dispatch(changeName(pk, name));
        },
        onToggle(pk, toggled) {
            dispatch(toggleConcert(pk, toggled));
        }
    })
)(DuplicateItem);


const App = () => (
    <div style={{ maxWidth: '1200px', margin: 'auto' }}>
        <DuplicatesTable />
    </div>
)

ReactDOM.render(
    <ReactRedux.Provider store={store}>
        <App/>
    </ReactRedux.Provider>,
    document.getElementById('app')
);

Lessons learned by doing this mini app when working with huge dataset

  • React components work best when they are kept small
  • Reselect become very useful to avoid recomputation and keep the same reference object (when using immutable.js) given the same arguments.
  • Create connected component for component that are the closest of the data they need to avoid having component only passing down props that they do not use
  • Usage of fabric function to create mapDispatchToProps when you need only the initial prop given in ownProps is necessary to avoid useless re-rendering
  • React & redux definitively rock together !

2
I don't think adding a dependency to redux is necessary to solve the OP's problem, further more dispatching actions for filtering his result set would only compound the problem, dispatches are not as inexpensive as you might think, handling this particular situation with local component state is the most efficient approach
deowk

4
  1. React in development version checks for proptypes of each component to ease development process, while in production it is omitted.

  2. Filtering list of strings is very expensive operation for every keyup. it might cause performance issues because of single threaded nature of JavaScript. Solution might be to use debounce method to delay execution of your filter function until the delay is expired.

  3. Another problem might be the huge list itself. You can create virtual layout and reuse created items just replacing data. Basically you create scrollable container component with fixed height, inside of which you will place list container. The height of list container should be set manually (itemHeight * numberOfItems) depending on the length of visible list, to have a scrollbar working. Then create a few item components so that they will fill scrollable containers height and maybe add extra one or two mimic continuous list effect. make them absolute position and on scroll just move their position so that it will mimic continuous list(I think you will find out how to implement it:)

  4. One more thing is writing to DOM is also expensive operation especially if you do it wrong. You can use canvas for displaying lists and create smooth experience on scroll. Checkout react-canvas components. I heard that they have already done some work on Lists.


Any info about React in development? and why checks for protoytpes of each component?
Liuuil


4

Like I mentioned in my comment, I doubt that users need all those 10000 results in the browser at once.

What if you page through the results, and always just show a list of 10 results.

I've created an example using this technique, without using any other library like Redux. Currently only with keyboard navigation, but could easily be extended to work on scrolling as well.

The example exists of 3 components, the container application, a search component and a list component. Almost all the logic has been moved to the container component.

The gist lies in keeping track of the start and the selected result, and shifting those on keyboard interaction.

nextResult: function() {
  var selected = this.state.selected + 1
  var start = this.state.start
  if(selected >= start + this.props.limit) {
    ++start
  }
  if(selected + start < this.state.results.length) {
    this.setState({selected: selected, start: start})
  }
},

prevResult: function() {
  var selected = this.state.selected - 1
  var start = this.state.start
  if(selected < start) {
    --start
  }
  if(selected + start >= 0) {
    this.setState({selected: selected, start: start})
  }
},

While simply passing all the files through a filter:

updateResults: function() {
  var results = this.props.files.filter(function(file){
    return file.file.indexOf(this.state.query) > -1
  }, this)

  this.setState({
    results: results
  });
},

And slicing the results based on start and limit in the render method:

render: function() {
  var files = this.state.results.slice(this.state.start, this.state.start + this.props.limit)
  return (
    <div>
      <Search onSearch={this.onSearch} onKeyDown={this.onKeyDown} />
      <List files={files} selected={this.state.selected - this.state.start} />
    </div>
  )
}

Fiddle containing a full working example: https://jsfiddle.net/koenpunt/hm1xnpqk/


3

Try filter before loading into the React component and only show a reasonable amount of items in the component and load more on demand. Nobody can view that many items at one time.

I don't think you are, but don't use indexes as keys.

To find out the real reason why the development and production versions are different you could try profiling your code.

Load your page, start recording, perform a change, stop recording and then check out the timings. See here for instructions for performance profiling in Chrome.


2

For anyone struggling with this problem I have written a component react-big-list that handles lists to up to 1 million of records.

On top of that it comes with some fancy extra features like:

  • Sorting
  • Caching
  • Custom filtering
  • ...

We are using it in production in quite some apps and it works great.


আমাদের সাইট ব্যবহার করে, আপনি স্বীকার করেছেন যে আপনি আমাদের কুকি নীতি এবং গোপনীয়তা নীতিটি পড়েছেন এবং বুঝতে পেরেছেন ।
Licensed under cc by-sa 3.0 with attribution required.