KubiGR
KubiGR

Reputation: 41

What's the difference between useObserver and observer in this application?

I have a react functional component that accesses the MobX store with useContext. I have found two ways to observe an array that is an observable from the store. First, the useObserver hook and wrapping the component with observer.

I thought that these are the same but that the useObserver only observes specific properties (such as the array that is passed) but I am experiencing a problem when the array reaches size 2 and then the component does not re-render. That's the case when using useObserver. When wrapping with observer, this is fixed.

Can anyone explain why this is happening and what's the difference?

const ApplesContainer = observer(() => {
    const stores = useStores();
    const applesArray = stores.fruits.apples;

    return (
            {applesArray.map(apple => (
                <Apple key={apple.id} apple={apple} />
            ))}
    );
});

// OR with useObserver()

function useGlobalState() {
    const stores = useStores();
    return useObserver(() => ({
        applesArray: stores.fruits.apples
    }));
}
const ApplesContainer = observer(() => {
    const { applesArray } = useGlobalState();

    return (
            {applesArray.map(apple => (
                <Apple key={apple.id} apple={apple} />
            ))}
    );
});

Upvotes: 4

Views: 2969

Answers (1)

JogaBonito
JogaBonito

Reputation: 21

useObserver must return JSX with an observable value. This hook takes care of tracking changes and re-rendering them. If no observable value exists in JSX, then it won't be re-rendered.

e.g.:

const SomeContainer =() => {
    const { someStores } = useStores();

    return useObserver(()=>(
            {someStore.data.map(val => (
                <Apple key={val.id} val={val} />
            ))}
    ));
};

Upvotes: 1

Related Questions