Skip to content

Understanding the Strict Mode Changes in React 18

Posted on:June 30, 2023

Table of contents

Open Table of contents

Strict Mode in React

Strict mode is not a new concept in React; it has been around since React 16. It operates exclusively during development and doesn’t affect your production build. Initially, strict mode involved certain checks, but with each React version, there was a plan to introduce additional features. React 18 follows this trajectory, as seen in the release notes.

The notable change in React 18 strict mode is that, previously, regardless of strict mode, React would mark a component once during mounting. Now, in strict mode, React will mount your component twice. Let’s delve into an example to understand why this change is introduced.

Practical Example

Consider a scenario where your React application uses strict mode, which is often the case in popular templates like Create React App. Let’s examine a component, a timer, that works well under strict mode.

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      setSeconds(prevSeconds => prevSeconds + 1);
    }, 1000);

    return () => {
      clearInterval(intervalId);
    };
  }, []);

  return <h1>Timer: {seconds} seconds</h1>;
}

This component displays the number of seconds elapsed since it was loaded. Now, let’s try to create a similar custom timer component and integrate it into our app.

function CustomTimer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    setInterval(() => {
      setSeconds(prevSeconds => prevSeconds + 1);
    }, 1000);

    console.log("Mounting");

    return () => {
      console.log("Unmounting");
    };
  }, []);

  return <h1>Custom: {seconds} seconds</h1>;
}

function App() {
  return (
    <div>
      <Timer />
      <CustomTimer />
    </div>
  );
}

Upon running this application, you might notice a peculiar behavior. While the imported Timer works as expected, the CustomTimer increments the seconds by 2 each second. This anomaly is due to the change in React 18 strict mode.

To diagnose the issue, we added logging statements within the CustomTimer component. Upon inspection, we found that the component was getting mounted, unmounted, and then mounted again. This behavior is a result of the change in strict mode.

What Strict Mode Helps With

Conclusion

React 18’s adjustment to strict mode, specifically in mounting components twice, serves as a valuable tool for catching subtle bugs. This example demonstrates how the change helps identify issues related to component lifecycle management, emphasizing the importance of proper setup and teardown in React applications. As you transition to React 18, be mindful of these changes and leverage them to enhance the robustness of your applications.