Daniel Amram
Daniel Amram

Reputation: 61

Usage of mobx in custom react hooks

We're using custom hooks in our app to invoke automatic analytics/general hooks which using const user = useObserver(() => userStore.user); to dispatch analytics (lifecycles of components/general usages)

But I have seen that useObserver hook of mobx is deprecated:enter image description here

Couldn't find any pattern for mobx usage with custom hooks (hooks can't use observer), it seems like the proper way is to pass the state through a component useCustomHook(user); which is not clean if we need to do it all over our components in the app.

Wonder what is the right pattern to do so with usage of mobx state in custom hooks.

Thank you.

Upvotes: 4

Views: 1681

Answers (1)

Velidan
Velidan

Reputation: 6004

You can use mobx reactions for this purpose as hooks are just functions and reactions are ideally fits in your requirements and doesn't need any bindings.

In your hook I'd use the React useEffect to setup a reaction but your should keep in mind that you should always dispose it to avoid memory leak. autorun is also possible but reaction gives to you a possibility to precisely control what exactly do you want to track.

Here is working playground where you can see the standard observer component and component with custom hook. Both reflect the mobx observable change.

The custom hook code from the playground:

const useCustomHook = (appState) => {
  // should reflect the appState value change
  const [valueType, setValueType] = useState("ZERO VALUE");

  useEffect(() => {
    // using mobx reaction in the hook (the reaction can be used anywhere)

    const reactionDisposer = reaction(
      // should pass the required store.
      // Could be done by DI, direct instance injection
      // or passing into hook from the parent component etc.
      () => appState.value,
      (value) => {
        if (value % 2) {
          setValueType("EVEN");
        } else {
          setValueType("ODD");
        }
      }
    );

    return () => {
      reactionDisposer();
    };
  }, []);

  return valueType;
};

Kind regards.

Upvotes: 0

Related Questions