Chuck
Chuck

Reputation: 452

ReactJS: Should a large array of objects be passed down to many levels of child components as props?

I'm looking at one of my colleague's ReactJs code and noticed that he is passing an array of custom objects down to 5 levels of child components as props. He is doing this b/c the bottom level child component needs that array's count to perform some UI logic.

At first I was concerned about passing a potentially large array of objects down to this many levels of component hierarchy, just so the bottom one could use its count to do something. But then I was thinking: maybe this is not a big deal since the props array is probably passed by reference, instead of creating copies of this array.

But since I'm kind of new to React, I want to go ahead and ask this question here to make sure my assumptions are correct, and see if others have any thoughts/comments about passing props like this and any better approach.

Upvotes: 8

Views: 3187

Answers (2)

Andrew G.
Andrew G.

Reputation: 418

In regards to the array being passed around I believe it is indeed a reference and there isn't any real downside to doing this from a performance perspective.

It would be better to make the length available on Child Context that way you don't have to manually pass the props through a bunch of components that don't necessarily care.

also it seems it would be more clear to pass only the length since the component doesn't care about the actual objects in the array.

So in the component that holds the array the 5th level child cares about:

var React = require('react');

var ChildWhoDoesntNeedProps = require('./firstChild');

var Parent = React.createClass({

  childContextTypes: {
    arrayLen: React.PropTypes.number
  },

  getChildContext: function () {
    return {
      arrayLen: this.state.theArray.length
    };
  },

  render: function () {
    return (
      <div>
        <h1>Hello World</h1>
        <ChildWhoDoesntNeedProps />
      </div>
    );
  }
});

module.exports = Parent;

And then in the 5th level child, who is itself a child of ChildWhoDoesntNeedProps

var React = require('react')

var ArrayLengthReader = React.createClass({

    contextTypes: {
      arrayLen: React.PropTypes.number.isRequired
    },

    render: function () {
      return (
        <div>
          The array length is: {this.context.arrayLen}
        </div>
      );
    }
});

module.exports = ArrayLengthReader;

Upvotes: 5

Cristian Sava
Cristian Sava

Reputation: 106

I don't see any problems with passing a big array as a props, even the Facebook is doing that in one of their tutorial about Flux.

Since you're passing the data down to this many lever you should use react contex.

Context allows children component to request some data to arrive from component that is located higher in the hierarchy.

You should read this article about The Context, this will help you with your problem.

Upvotes: 2

Related Questions