Heimot
Heimot

Reputation: 61

StrictMode causing useState to break

StrictMode breaks useState inside of useEffect. Without StrictMode or in build the code works fine.

The setIsLoading should set the state to false in useEffect. setIsLoading(false) "would fix this" but it doesnt explain why the setIsLoading(prevState => !prevState) sets it back to true. Does this only happen because of the StrictModes double render? Or is there a better way to do this?

import { useEffect, useState } from "react";

export default function App() {
  const [isLoading, setIsLoading] = useState<boolean>(true);

  useEffect(() => {
    const getData = async () => {
      /*
        Some random code would be here
      */
      setIsLoading((prevState) => !prevState);
    };
    getData();
  }, []);

  return (
    <div className="App">
      {isLoading ? <div>Loading...</div> : <div>Data has been loaded</div>}
    </div>
  );
}

Here's a link to a codesandbox if you want to try it out. https://codesandbox.io/p/sandbox/bug-test-39l53k?file=%2Fsrc%2FApp.tsx

Upvotes: 1

Views: 66

Answers (1)

0lli.rocks
0lli.rocks

Reputation: 1072

Yes, StrictMode is the reason why your isLoading is reset, since the useEffect gets called twice.

What StrictMode does is:

  • Your components will re-render an extra time to find bugs caused by impure rendering.
  • Your components will re-run Effects an extra time to find bugs caused by missing Effect cleanup.
  • Your components will be checked for usage of deprecated APIs.

Source

So based on what you want to do, setting isLoading to false could be the correct way to fix your issue.

Upvotes: 1

Related Questions