sop ian
sop ian

Reputation: 95

React and Redux Architecture

I have questions about React and Redux architecture.

Suppose you have normalized data

const user = [
  { userId: 1, name: 'Ian', groupId: 1 },
  { userId: 2, name: 'Tom', groupId: 2 }
]

const groups = [
  { groupId: 1, groupName: 'Facebook developers'},
  { groupId: 2, groupName: 'Google developers'}
]

const chat = {
  { userIdFrom: 1, message: 'Hello!', timestamp: 1324132332 },
}

What is the best practice to manipulate data such as .map, .filter, .reduce, .forEach, .sort, denormalization etc?

I create utils functions to handle huge data manipulation like Utils.getChatsFromUsers etc and invoked from render method on Component.

Is this my solution good practice to handle huge and many data manipulation in Component's render function?

Please give me your advise and insight. Thanks!

Upvotes: 1

Views: 201

Answers (1)

Thales Gaddini
Thales Gaddini

Reputation: 167

It is not really a good practice to manipulate arrays inside the render method unless the array is the only thing being rendered, or if the array is the prop the will most likely change. You should manipulate them in the componentWillReceiveProps.

So, instead of having something like this:

render() {
    const { string1, string2, string3, array } = this.props;
    const mappedArray = array.map(element => <li>{element}</li>);
    return (
      <div>
        <p>{string1}</p>
        <p>{string3}</p>
        <p>{string3}</p>
        <ul>{mappedArray}</ul>
      </div>
  );
}

you should do something like this:

componentWillReceiveProps(nextProps) {
  // R is from ramda, but you can compare the arrays any way you want
  // even just comparing the array references if that's good enough for you
  if (R.equals(nextProps.array, this.props.array)) {
    this.mappedArray = array.map(element => <li>{element}</li>);
  }
}

render() {
    const { string1, string2, string3, array } = this.props;
    return (
      <div>
        <p>{string1}</p>
        <p>{string3}</p>
        <p>{string3}</p>
        <ul>{this.mappedArray}</ul>
      </div>
  );
}

This way you avoid having to recreate the mapped array every time the render method is called (which could happen from other props changing or the state being changed).

This topic is covered here.

Upvotes: 1

Related Questions