Search code examples
reactjsmobxmobx-react-lite

Can I totally get rid of useCallback and useMemo with MobX in React?


Currently, I am using Redux and the mentioned hooks for react projects. However, useMemo and useCallback can quickly lead to bugs (tricky ones) very quickly in my opinion. As I understood, these hooks are required to avoid unnecessary re-rendering of components since react is checking referential equality.

I want to get rid of the above-mentioned hooks and let MobX handle all the reactive stuff. I wonder if I totally can get rid of them (useCallback, useMemo) and therefore everything updates automatically.

  1. Does MobX come with slower performance?
  2. Is it even possible to totally get rid of them with MobX?
  3. Can UI components also only relay on MobX (e.g. setting loading boolean or boolean for toggle modal visibility)?

Also, I read useContext should not be used for high frequent updates. However, MobX is really often used with the hook (talking about mobx-react-lite). So is it even a good idea to use MobX for UI updates?


Solution

  • First of all you do not really need those hooks.

    • useMemo - is for laziness value, nothing will happen if you decide to ditch it and simply get your value.

    • useCallback - like useMemo for functions, again you can declare a function without wrapping it in useCallback function.

    From React useMemo and useCallback

    You may rely on useMemo as a performance optimization, not as a semantic guarantee.

    useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).

    For 99% of the cases those hooks are use for optimizations, they are not related to MobX or Redux and you can simply not use them. unless you have a very specific use case that other questions in StackOverflow are suggesting you to use them.

    I personally hate redux, it sounds good at first but than you realize it is a big monster to continuously maintain.

    MobX takes another approach to manage global state of your app that also sounds good at first but then you dive in and see the implementation with a tweak of useState to trigger forceRender and use some voodoo with observable wrapper function component.

    That's why I have recently created a simple react state management package that in my opinion way too simple to understand maintain and scale(I use this pattern in several large apps)

    It is called react-spear.

    I would really appreciate to hear any thoughts of it, I think this approach makes global state management really easy.