1

I am writing a React+react-query application today and I am running into a problem when I switched from development mode to production mode.

Production mode is a mix of running npm run build and serving those HTML/JavaScript/CSS files inside a serve (maybe using npx serve dist). Development mode is just running npm run dev (or npm start if using CRA).

This is the code:

const useMyQuery = () =>
  useQuery(
    ["myAwesomeData"],
    async () => {
      const { data } = await axios.get(`http://http.us/500`);
      return data;
    },
    { placeholderData: { myAwesomeProperty: [] } }
  );

const App = () => {
  const { isError } = useMyQuery();
  return isError ? <div>Error</div> : <Child />;
};

const Child = () => {
  const { data } = useMyQuery();
  return (
    <pre>
      <code>{JSON.stringify(data.myAwesomeProperty)}</code>
    </pre>
  );
};

For the sake of simplicity, I omitted QueryClientProvider and its client. Also placeholderData is being used as a loading state, which allows Child to be properly rendered while real data is loading.

The most important part here is data.myAwesomeProperty AFTER the loading state - which throws an error ONLY when running in production. The error produced is:

TypeError: Cannot read property 'myAwesomeProperty' of undefined

When running on development, the <div>Error</div> appears as expected.

My main concern here is NOT solve the problem (as I could simply add a if statement on Child component to prevent accessing data.myAwesomeProperty).

Instead, I would like to know why there is a difference between development's and production's behavior? Is it documented somewhere?

richardaum
  • 6,651
  • 12
  • 48
  • 64
  • 1
    Is there a reason you're quoting all this text? It kinda looks like it's just your own text, just... use regular text? (and use code fences, or code indentation, for that TypeError) – Mike 'Pomax' Kamermans Sep 06 '21 at 22:33

1 Answers1

2

The dev and prod version of React has quite a bit difference. But the main one can be the speed here. In general the prod version is a lot more performant.

Based on the way you write, there's no way you should expect a valid myAwesomeProperty. So in the prod, you get the error right away.

In the dev, maybe things slow down, when you get the Child, the API already finishes.

NOTE: list coupe of dev/prod difference.

I also notice in the strict mode, things can be rendered twice, My React Component is rendering twice because of Strict Mode

This might answer if you don't get an error, since the double render actually happened in one update (not two updates).

windmaomao
  • 7,120
  • 2
  • 32
  • 36