-
In the production environment we have migrated from injections to using the useObserver hook to access the global store and its children. There was a bug in which an observable array stopped re-rendering the component when it reached a length of 2 (additions or removal did not trigger update until it was back at length 1). The same component worked when the observer HoC was used. I tried reproducing the problem but I could not reproduce that specific bug but I am providing these two sandboxes and I am asking if someone can help me understand why the useObserver hook is not re-rendering (unless the state of the component somehow changes). observer HoC sandbox: https://codesandbox.io/s/zen-zhukovsky-xntjc I was not the one that chose useObserver as the way to implement this but there is a notion (where I work) that the useObserver hook seems more clear since specific observables are chosen. Still it produces problems that I do not understand in contrast to the observer HoC and I am trying to understand them fully in order to decide what's the best solution. mobx: 5.15.6 (I know that 4/5 mobx support has stopped but I would still value an answer) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
function useGlobalState() {
const stores = useStores();
return useObserver(() => ({
todos: stores.childStore.todos
}));
}
export const TodosContainer = () => {
const { todos } = useGlobalState();
return (
<>
<h1>TODOS</h1>
{todos.map((todo) => (
<Todo key={todo.id} todo={todo} />
))}
</>
);
}; This is exactly the antipattern that we wanted to get rid of and why we deprecated To make that work you would have to do |
Beta Was this translation helpful? Give feedback.
-
Sorry for the reply deletion but I am wrapping these all in a comment. Thanks for the rapid response. Indeed toJS works and correct me if I understand wrong but it works because now the hook returns a normal JS array than just a reference (and it updates it upon new changes). So useObserver can be safely used on primitives or is that also a bad choice? I read in the documentation the observer HoC is using useObserver underneath. What's the difference? Indeed, I will try to use observer HoC from now on and thank you very much for you help! |
Beta Was this translation helpful? Give feedback.
This is exactly the antipattern that we wanted to get rid of and why we deprecated
useObserver
. If you use it like this then you are observing only what's wrapped in theuseObserver
, in your case nothing. You are only returning a reference to a list of todos. Only the actual iteration over it and accessing those will trigger reactivity, but there is…