cerebral / overmind

Overmind - Frictionless state management
https://overmindjs.org
MIT License
1.58k stars 95 forks source link

Lessons learned (useful for documentation?) #516

Closed grandevel closed 2 years ago

grandevel commented 3 years ago

Per @christianalfoni's request in discord... documenting some quick lessons learned from when I inherited an Overmind/React app. Initial Path Count > 62k and 9k connected components. App performance was mediocre. With 1 hour's work, it was possible to take the path count and connected components down to ~3k (95% saving on state access and proxy tracking overheads) and 1k connected components. Mem usage down, and app speeds significantly improved.

Main wins worth me documenting...

The key is to absolutely avoid using .find(x => x.id === someId) in sub components (like a TodoItem or a Todo list). The worst example is to {todoList.map(item => { return { }}) - and then in the to pull the list from state and todoList.find(item => item.id === id) to get the object you are going to bind to the render.

A lighter approach typically seems to work better when passing props - pass id's, rather than objects themselves, and grab them from state directly using the object-as-list: state.todoList[id].

const listToObject = (list, prop) => { return list.reduce( (a: Object, c: Object) => { const id = c[prop];

  if (a[id]) return null; // We could not do this - the key provided is not duped - throw some sort of exception here
  a[id] = c;
  return a;
},

Two options exist to add a list of all keys - use Object.keys, or create a .all property with a list of ID's.

Example: fetching todos from the server every 5 seconds returns a list of 20 todo objects. 1 of them changes, bad thing you can do from a path tracking perspective is update the whole list object and cause a widespread re-render. So, instead, consider whether it is better to just take the hit, or better compare the sub-properties (i.e. each item) between objects and just update those sub properties which have changed without updating the root object containing the list.

Use Overmind devtools to check your path, flush and connected component counts - biggest win for this app in my case.

grandevel commented 2 years ago

Closing my own issue here, probably will do a small video series on this stuff

nkint commented 2 years ago

@grandevel interesting, thanks for sharing. I remember I had similar problems with mobx. Update this issue when you have made the videos, thanks! 🙏