Tom
Tom

Reputation: 2661

correct way to lay out a state in React

In my project I want to display a list of groups. Each group has different tasks with dependencies (or not) to other tasks. The list I get from the database looks like this:

{ 
    "id": 1, 
    "group": "Before breakfast", 
    "task": "scramble eggs", 
    "dependencyIds": [], 
    "completedAt": false 
}, 
{ 
    "id": 2, 
    "group": "Before breakfast", 
    "task": "Cook Eggs", 
    "dependencyIds": [ 1 ], 
    "completedAt": false 
},
{ 
    "id": 3,
    "group": "After breakfast",
    "task": "Do the dishes",
    "dependencyIds": [ 1, 2],
    "completed": false 
}

One solution would be to just write the entire data as an array into the state. But that means, every time when I complete a task, I filter through the entire array and have to update the entire state. Hence I was wondering if it's more efficient if I filter and sort the data after I fetched it from the database. The state would look like this then:

this.state = {
      "Before Breakfast": [
        {
          id: 1,
          title: "scramble eggs",
          completed: false,
          dependencies: []
        },
        {
          id: 2,
          title: "cook eggs",
          completed: false,
          dependencies: [1]
        }
      ],
      "After Breakfast": [
        {
          id: 3,
          title: "do the dishes",
          completed: false,
          dependencies: [1, 2]
        }
      ]
    };

My idea was that now only the group object with the task has to be updated, not the entire state.

Does this make sense or is it unnecessarily overcomplicating the code?

Upvotes: 1

Views: 53

Answers (1)

mliakos
mliakos

Reputation: 383

Well, I don't see how that could help with performance or something, since React will only change (rerender) only what's needed, when comparing virtual DOM to the real one. And it's plenty fast, I think you should ommit filtering if its not needed anyway.

Upvotes: 1

Related Questions