samedi 30 janvier 2021

Normalizing State with React useState?

Is this a common practice and generally recommended, also for useState?

Would it generally be advisable to turn this...

{
  "id": "123",
  "author": {
    "id": "1",
    "name": "Paul"
  },
  "title": "My awesome blog post",
  "comments": [
    {
      "id": "324",
      "commenter": {
        "id": "2",
        "name": "Nicole"
      }
    }
  ]
}

...into something like this:

{
  result: "123",
  entities: {
    "articles": {
      "123": {
        id: "123",
        author: "1",
        title: "My awesome blog post",
        comments: [ "324" ]
      }
    },
    "users": {
      "1": { "id": "1", "name": "Paul" },
      "2": { "id": "2", "name": "Nicole" }
    },
    "comments": {
      "324": { id: "324", "commenter": "2" }
    }
  }
}

(example taken from here)

I know this was a thing with redux, but I'm struggling to decide whether it makes sense with newer things like useState, useReducer or just Reacts context api etc.

In my use case, it seems like I could benefit from doing it this way, but not by so much, since the way I want to show the data sort of concurs with the way it comes back from the backend.

Aucun commentaire:

Enregistrer un commentaire