mobxmobx-react

Why are React components rendering twice when wrapped with observer()?


Simply wrapping React components with observer() seems to cause them to render twice. What could the possible reasons for this be? I am running the latest versions of react 16.8.3, mobx 5.9.4 and mobx-react-lite 1.2.0

For example:

import React from "react";
import { observer } from "mobx-react-lite";

const Item = observer(() => {
  return (
    <div>
      {console.log("render item")}
      Item
    </div>
  );
});

export default Item;

This is occurring in a relatively complex application. I noticed the behavior while debugging another problem. I then removed as much code as possible and was able to reproduce the problem in a very simple case.

EDIT: See the answer below. I was able to determine the problem by attempting to repo using codesandbox.


Solution

  • I should have finished the codesandbox I was working on before posting the question although this may save someone else the pain and wasted time. It turns out that the reason the double renders are occurring is because I'm using React.StrictMode. Interestingly, the double renders with React.StrictMode only seem to occur when the component is wrapped with observer() Here is the codesandbox. React.StrictMode is used around the entire app (index.js) and if removed, the double renders stop.