javascriptreactjsmobxmobx-reactmobx-react-lite

Why can't we use React.useMemo in mobx-react to keep reference to the state object?


Currently my project is still using mobx@4 and mobx-react@6 and I found this warning in the documentation:

Fair warning. Don't ever use React.useMemo to keep reference to the state object. It may be randomly thrown away by React and you may lose data.(mobx-react documentation)

I can't understand it, can anyone help with an example and the reason why?


Solution

  • Quote from React docs:

    You may rely on useMemo as a performance optimization, not as a semantic guarantee. In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without useMemo — and then add it to optimize performance.

    Basically React can reinstantiate memoized value at any time if it wants to and you will lose your whole Store because it will be recreated with default parameters.

    It might not do it right now, but it is better not use memo for persistent values so you won't be forced to make refactoring if you migrate to future versions of React.

    Link: https://reactjs.org/docs/hooks-reference.html#usememo