React StrictMode

Learn via video courses
Topics Covered

Overview

A React developer tool called StrictMode is mostly used to find possible problems in web applications. It initiates additional deprecation tests and warnings for its child components. One of the factors contributing to its popularity is the fact that it provides warning/error messages in the form of visual responses, whenever the React rules and advised practices are not followed. Like the React Fragment, the React StrictMode Component doesn't render any visible UI.

What is React StrictMode?

The main purpose of the React Developer Tool StrictMode is to draw attention to potential issues in a web application. For its child components, it turns on additional deprecation checks and warnings. Its ability to display visible feedback (warning/error messages) whenever the React rules and suggested practices are not followed is one of the factors contributing to its popularity. The React StrictMode Component does not render any visible UI, just like the React Fragment. React StrictMode can be thought of as a tool that aids developers in creating code quickly and alerts them to any questionable code that might have been unintentionally contributed to the application. The StrictMode need not be applied to the entire program; it can be applied to any part of it. Utilizing it is extremely beneficial while creating new scripts or debugging an application.

Example

Explanation

StrictMode tests will only apply to Components 2 and 3 in the case above (as they are the child components of React.StrictMode). Components 1 and 4 won't be subject to any checks, though.

Advantages

During the development phase, the React StrictMode assists in identifying and detecting a variety of warnings and problems, including:

It is deemed risky to employ some legacy component lifecycle methods in async applications. The React StrictMode assists in identifying the use of such risky techniques. When enabled, a list of all components implementing risky lifecycle techniques is shown as a warning message.

1. Aids in identifying components with risky lifecycles

It is deemed risky to employ some legacy component lifecycle methods in async applications. The React StrictMode assists in identifying the use of such risky techniques. Once activated, a list of all components implementing risky lifecycle techniques is shown as a warning message.

2. Warns against using the dated string ref API

There were initially two ways to manage refs: the callback API and the legacy string ref API. Later, a third alternative way, known as the createRef API, was introduced. This approach used object refs instead of string refs, allowing the StrictMode to issue warnings anytime string refs are used.

3. Warns against using the out-of-date find DOMNode

It is not possible to handle changes when a child component tries to render a different node since the findDOMNode API can only be used once (other than the one rendered by the parent component). React StrictMode identified several problems and flagged them for display as warnings.

  • The StrictMode only functions in development mode because it is a developer tool. It has no impact on the production build.
  • StrictMode renders every component of the program twice to find and detect any issues and display warning messages

How to Use it?

In React, A tool called StrictMode identifies potential problems in software. It functions by isolating a piece of your complete program and using it as a component. In development mode, StrictMode does not render any elements that can be seen in the DOM, but it does enable checks and issue warnings.

In production mode, StrictMode doesn't run any tests or issue any alerts.

Example

React strict mode does not show any visible UI, therefore it only offers developers warnings as feedback for mistakes that occur in an application. The framework received new functionality in React version 18.0 while also receiving considerable improvements to several already-existing capabilities.

Strict React Mode runs a few functions in the development environment to make sure they have no unwanted side effects and return values that match the required inputs. The following features are supported in StrictMode as of React v17:

  • Recognising historical string references.
  • The findDOMNode function is no longer supported.
  • It has been discovered that the old Context API is being used.
  • Identifying risky lifecycle techniques that React has abandoned.
  • Unexpected side effects are found in React components.

What Does React Strict Mode Help With?

Identifying Unsafe Lifecycles

Version 16.3.0 of the React APIs included several notable changes. One of these changes was the discontinuation of lifecycle methods like componentWillMount, componentWillReceiveProps, and componentWillUpdate. Additionally, new lifecycles like getSnapShotBeforeUpdate and getDerivedStateFromProps were added.

Future revisions of React may completely delete these lifecycle routines, even though they have been given the prefix UNSAFE_ and are still accessible.

What were the reasons these lifecycle methods were deprecated? To grasp this, we must first understand that React works in two stages:

Render Phase

React checks which DOM modifications are necessary before rendering. React calls a render function` at this stage and contrasts the output with the previous one.

Commit Phase

React calls lifecycles associated with the commit phase, such as componentDidMount and componentDidUpdate, during this phase and applies the modifications to the DOM.

The render phase might be time-consuming, whereas the commit phase is short. To prevent the browser stoppage and optimize the browser performance for concurrent mode, React chose to break up the rendering process into pieces and pause/resume the work as per requirements.

As a result, the render phase lifecycles may be called multiple times, which could cause the application to function erratically. Especially when they have negative impacts or employ improper techniques in processing. Additionally, some of these lifecycles encourage unprofessional developer behavior. Here are a few examples:

  • componentWillMount
  • componentWillReceiveProps
  • componentWillUpdate

To assist you in reworking your code, a code-mod will rename any unsafe lifecycles and add the UNSAFE_ prefix; however, keep in mind that this just removes the warning, not the use of an unsafe lifecycle.

Class-based lifecycle functions in React have undergone several API modifications. Many once-commonly used methods are now formally deprecated and discouraged in favor of more up-to-date APIs.

Developers that use certain out-of-date APIs, such as componentWillMount, componentWillReceiveProps, and componentWillUpdate, will now receive warnings from React strict mode. These are currently viewed as being risky to use, to the point where React has prefixed the names of these APIs with the word UNSAFE.

Even better, react strict mode will alert programmers if any of the third-party packages being used include these obsolete APIs. You have the option of altering those packages yourself or going another route.

Warning About Legacy String ref API Usage

In earlier iterations of React, references were allocated using strings. Dan Abramov drew attention to the fact that there were further problems. React must maintain track of the component that is presently rendering because it is unable to guess. This causes React to slow down a little.

Since the ref is added to List for the same purpose, the render callback pattern (such as List renderRow=this.renderRow />) does not function as most people would anticipate. As a result, if a library adds a ref to the passed child, the user cannot add another because it is not composable. Referees for callbacks are easily interchangeable.

Better solutions for class components were introduced due to this and other factors, such as the difficulty with typing refs in TypeScript where they must be cast:

  • Callback refs
  • React.createRef

When class-based architecture was the standard method for building components when using React, you might have utilized the string ref API as follows:

Example

This API is now regarded as a legacy for several reasons, while being readable and practical to use, including:

  • A wrapped component is unable to determine whether its child component has an existing ref. An answer to this issue is a callback ref pattern.
  • Reading the string ref API and using a type checker for static analysis can be challenging.

React strict mode advises programmers to utilize the more up-to-date create API or a callback mechanism instead.

Warning About Deprecated findDOMNode Usage 

A class instance could be used to search the tree of DOM nodes using the FindDOMNode functionality in React.

This strategy has a few drawbacks. The first is that refactoring may become problematic. If a parent component used findDOMNode to fetch a child element, it used to be aware of the implementation details of its children. The second issue is that, while in the world of fragments, several children are occasionally rendered by one component, findDOMNode only returns the first child found. FindDOMNode is typically not required because you can always construct a ref directly to a DOM node (as was previously demonstrated).

You can construct a ref and use Ref Forwarding in your custom component to get the underlying DOM element if you need anything like findDOMNode. A deep-level element in the DOM tree can be targeted from any component using the class-based API findDOMNode.

Example

Although it may appear to be fine, this violates the abstraction principle of React.

The parent element must make sure that its children are rendering the correct DOM nodes at all levels. The fact that findDOMNode is a one-time calling API only has the significant drawback that if any node element changes as a result of a future state update, the change won't be reflected and updated by the findDOMNode API.

Given all these drawbacks, react strict mode advises against using this API and notes that it might be removed in the next React releases. The DOM element can now typically be targeted using ref. You may easily target an element by adding a ref reference to it.

Example

Detecting Unexpected Side Effects

As we saw in the previous section, React chose to separate the rendering step to optimize the rendering stage in the upcoming Concurrent Mode. Renderer stage specs can therefore be called several times, which could lead to unforeseen outcomes if negative effects are applied.

The most recent version of React has these features:

  • constructor
  • getDerivedStateFromProps
  • shouldComponentUpdate
  • render
  • both class and functional components provide setState updater methods.
  • functions passed to useMemo, useState, seducer

Although side effects are unpredictable, StrictMode aids in making the developer a little more predictable by twice running the aforementioned functions. As a result, due to the obvious discrepancies, if a side effect is accidentally written in a rendering phase function, it may end up in Development Mode.

Consider the case where a WebSocket connection is established in a function. In that scenario, since two connections are made, a double execution of the function in Development Mode can help to make it easier to recognize.

The react strict mode of React does some intriguing actions about well-known built-in hooks like useState, useMemo, and useReducer. In particular, it calls these routines once in production mode and twice while in development mode. While reacting in strict mode make sure to check for any memory leaks by doing this, it may cause some confusion while debugging the code. It also aids in making strict mode code more deterministic.

The same behavior of calling functions twice is not restricted to functional components; it also occurs in class-based design in places like constructor function, render, shouldComponentUpdate, and other places. When utilizing a create-react app, react strict mode is automatically enabled for the entire program.

You may notice that even console messages are logged twice when utilizing these hooks or the state updater procedures in class components. When the functions were called twice in versions before 18, React was used to instantly stop the second console.log method. But as of version 18, React doesn't suppress any logs to increase developer openness. All of those logs are now called twice when any functions, hooks, etc. are called twice.

Warnings on the legacy context API

A new Context API was introduced in React 16.3. Before, if a component somewhere in the parent hierarchy implemented shouldComponentUpdate, it prohibited re-rendering of the children element and the prior error-prone API prevented consumers from updating.

Although the old Context API is still supported by React v16.x, StrictMode will flag any instances of it with warnings so that they can be updated to the most recent version.

We also have a legacy context API, which is related to the references API. The use of legacy context API is discouraged by reacting in the strict mode because it will be removed from upcoming releases. We have a newer, provider-consumer-based context API in place of that.

Example

Using the new context API is now the suggested method for managing app state context.

How to Enable React Strict Mode?

A tool that only operates in development mode is called React Strict Mode. It examines and flags potential problems in your application, such as dangerous lifecycles and the use of antiquated APIs. React Strick Mode is enabled by default for the entire application in Next.js. Although helpful, you might find it a touch bothersome at times (such as some repetitive warnings that overflow and mess up your console).

By entering your next.config.js file and changing the reactStrictMode option to false or true, respectively, you may enable or disable React Strict Mode:

Example

Wrapping a few particular components or pages in <React.StrictMode> and </React.StrictMode> will enable you to use React Strict Mode for those parts or pages:

Example

When strict mode is enabled, React will run additional checks and warnings for potential issues in the application such as:

  • Detecting unexpected side effects in the component render.
  • Detecting unexpected use of legacy string ref API.
  • Detecting unexpected dependencies in effect hooks.
  • Detecting missing keys in iterators.

It's worth noting that React Strict mode is only intended to be used during development and it is not recommended to use it in production as it may cause performance issues.

That's how easy it is! To ensure that all of the components are included, utilize the StrictMode component at the top of your DOM structure.

After turning on strict mode, you might wish to restart your application and check the console tab of the developer tools to see whether anything was discovered.

Comparison between React Strict Mode and Use Strict

You can include use strict at the start of a script or function to indicate that a code block should be executed in strict mode. Strict Mode, on the other hand, eliminates silent errors and throws errors when they occur to identify faults in code patterns and mark previously acceptable "faulty code patterns" as problems. React In that it ensures a more rigid and type-safe version of JavaScript, strict mode functions similarly to the use strict expression in JavaScript.

The table below outlines the connection between React Strict Mode and the use strict expression:

React Strict Mode

In React Strict mode, undeclared variables will produce an error. It looks for the following things:

components whose lifecycles are dangerous. usage of out-of-date or obsolete APIs or techniques, such as the findDOMNode and string ref APIs. unintended consequences.

You can import StrictMode from react in your code or use React.StrictMode to refer to the Strict Mode. The component can then be referred to as StrictMode.

As demonstrated in the code block below, enclose the questionable code in the Strict Mode helper component.

Example

Use Strict

The following are errors that are highlighted by the phrase use strict:

  • Giving undefined variable values.
  • Use of descriptive adjectives, like public in variable names
  • Updating constant variables with data.
  • Use a variable before its declaration, etc.
  • Because arguments is a reserved terms and variable x is not specified, both of the statements in the code sample below will result in errors.

Additionally, for it to be effective, "use strict" needs to be mentioned at the file's top.

Example

React Strict Mode is a tool provided by React for highlighting potential problems in a React application, whereas "use strict" is a JavaScript feature for enabling strict mode in the entire script. React Strict Mode is specifically designed to help developers find potential problems with their React code, such as unexpected side effects in component render, unexpected use of legacy string ref API, unexpected dependencies in effect hooks, and missing keys in iterators. It also provides additional warnings and checks that are not present in the normal development mode.

use strict is a JavaScript feature that enables a strict mode in the entire script. It helps to prevent certain actions from being taken and throws more exceptions. It eliminates some JavaScript silent errors by changing them to throw errors. It also fixes mistakes that make it difficult for JavaScript engines to perform optimizations. In summary, React Strict Mode is a tool for React applications specifically, whereas use strict is a feature for JavaScript in general. While React Strict mode is intended for development only, use strict is intended for production.

Conclusion

  • React Strict Mode is a tool provided by React for highlighting potential problems in a React application.
  • It is intended to be used during development, not in production.
  • The following features are supported in StrictMode as of React v17:
    • Recognising historical string references.
    • The findDOMNode function is no longer supported.
    • It has been discovered that the old Context API is being used.
    • Identifying risky lifecycle techniques that React has abandoned.
    • Unexpected side effects are found in React components.
  • It runs additional checks and warnings for potential issues in the application such as detecting unexpected side effects in component render, unexpected use of legacy string ref API, unexpected dependencies in useEffect hooks, and missing keys in iterators.
  • It can be enabled by wrapping a part or all of the application in a <React.StrictMode> component.
  • It is different from the use strict feature in JavaScript, which enables a strict mode in the entire script and is intended for production.
  • React Strict Mode is a great tool for finding and fixing errors in your React code to improve the overall quality of your application.