Search code examples
mobxmobx-react

Can I create a mobx computed inside a React render function to use like useMemo()?


I'm wondering how to go about using a mobx observable inside a useMemo hook. I know I could pass all possibly dependencies to the hook, but that could get kind of messy:

const MyComponent = observer(() => {
  const people = useGetPeople();
  const peopleFormatted = useMemo(() => {
    return people.map(person => person.fullName);
  },[ ...? ]);
});

I can't easily make every person's firstName be a dependency of useMemo. I'd think I could extract the functionality to a computed ... but I feel like this won't work:

const MyComponent = observer(() => {
  const people = useGetPeople();
  const peopleFormatted = computed(() => {
    return people.map(person => person.fullName);
  });
});

I feel like it will confuse mobx to create a computed inside a reaction that the reaction must depend on.

I know I could extract the computed to each person but I don't feel like that's a solution that matches every use case.

Thanks in advance!


Solution

  • Assuming const people = useGetPeople(); is an observable array of some sort of people objects...

    const peopleFormatted = computed(() => {
        return people.map(person => person.fullName);
      }).get(); //note .get()
    

    Should work fine inside the observer function body. See https://mobx.js.org/computeds-with-args.html#2-close-over-the-arguments

    What is confusing me is useGetPeople();

    That typically means you are using react's state api for managing state and reactions. ie: useState, etc.

    Without seeing what useGetPeople() does under the hood, it's hard to give a concrete answer.