TanStackT
TanStack2y ago
12 replies
brilliant-lime

How to handle nested objects without re-render the whole app?

App example: user has columns, columns has todos, each todo has a done checkbox that can be toggled on and off, basic stuff

How should I manage the requests to this use-case? One request to fetch all data? or split the data fetch into individual requests for each column?

At some point, the entry data will have to be refetched/mutated/optimistic updated, and this will change the entry data reference and trigger a re-render to my whole app.

If I toggle one todo at column #85, all columns and all todos will be re-rendered.

Is there a way to subscribe a column/todo to his slice of that big nested entry data object only?

I'm rendering the columns like this user.columns.map(column => <Column key column={column} />), so the column knows which slice of the big nested entry data object his data belongs, and must not be re-rendered if his slice didn't changed.

The solution I came up with is to use React.memo, deep comparing the column prop to check if his slice have changed in these re-renders. This leads to only the <Column /> with the changed column props to be re-rendered.

Is it right? I feel like I'm missing something here.

I would like to put this single pieces of data together in one single root source, is easy to work this way.

A addNewColumn() method must have a validation user.columns.getAmount() < user.plan.maxColumnsAllowed. Creating these front-end business rules with all data in one source is a super easy.

Yes, I know re-render is not a bad thing but in my real use-case, I have a lot of "columns", each "column" have a lot of "todos", each "todo" has their own universe, their data, their modals, their dropdowns, their hooks... Re-render the whole list everytime a small change happened... If this is not a performance concern, I don't know what should be.

I put together this small POC.
https://github.com/vitormarkis/37react-query-best-practices-nested-objects

You can see in the GIFs, the behavior with and without React memo.
nested-objects-bad.gif
nested-objects-good.gif
GitHub
37react-query-best-practices-nested-objects. Contribute to vitormarkis/37react-query-best-practices-nested-objects development by creating an account on GitHub.
GitHub - vitormarkis/37react-query-best-practices-nested-objects: 3...
Was this page helpful?