ReactJS - Strict Mode: A Beginner's Guide

Hello, future React developers! Today, we're going to dive into an important but often overlooked feature of React: Strict Mode. Don't worry if you're new to programming – I'll guide you through this concept step by step, just like I've done for countless students over my years of teaching. So, grab a cup of coffee (or tea, if that's your thing), and let's embark on this learning adventure together!

ReactJS - Strict Mode

What is Strict Mode?

Before we delve into the specifics, let's understand what Strict Mode is in React. Imagine you're learning to drive. Strict Mode is like having a very thorough driving instructor sitting beside you, pointing out every little mistake you make. It's not there to scold you, but to help you become a better driver – or in our case, a better React developer.

Strict Mode is a tool for highlighting potential problems in your application. It activates additional checks and warnings for its descendants. Let's see how to use it:

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

In this example, we're wrapping our entire App component with React.StrictMode. This means all components inside App will be subject to these additional checks.

Now, let's explore what Strict Mode actually checks for.

Unsafe Lifecycle Usage

What are Lifecycles?

Before we talk about unsafe lifecycles, let's understand what lifecycles are. In React, components go through a series of stages from birth (mounting) to death (unmounting). These stages are called lifecycles.

Unsafe Lifecycles

Some lifecycle methods are considered unsafe because they can lead to bugs in async rendering. Strict Mode helps identify their usage. Here's an example:

class OldComponent extends React.Component {
  componentWillMount() {
    console.log("This method is unsafe!");
  }

  render() {
    return <div>Hello, I'm an old component!</div>;
  }
}

If you use this component in Strict Mode, you'll see a warning in the console about using the unsafe componentWillMount lifecycle method.

Instead, you should use safer alternatives. Here's a table of unsafe methods and their safe alternatives:

Unsafe Method Safe Alternative
componentWillMount componentDidMount
componentWillReceiveProps static getDerivedStateFromProps
componentWillUpdate getSnapshotBeforeUpdate

Legacy Ref API Usage

What are Refs?

Refs provide a way to access DOM nodes or React elements created in the render method. They're like a direct line to a specific part of your UI.

String Refs (Legacy)

In the past, refs were created using strings, like this:

class OldButton extends React.Component {
  componentDidMount() {
    this.refs.myButton.focus();
  }

  render() {
    return <button ref="myButton">Click me!</button>;
  }
}

This method is considered legacy and can cause issues. Strict Mode will warn you if you're using string refs.

Modern Ref Usage

Instead, you should use the createRef API or the useRef hook:

class ModernButton extends React.Component {
  constructor(props) {
    super(props);
    this.myButton = React.createRef();
  }

  componentDidMount() {
    this.myButton.current.focus();
  }

  render() {
    return <button ref={this.myButton}>Click me!</button>;
  }
}

In this example, we're using React.createRef() to create a ref, which is much safer and more efficient.

Legacy findDOMNode Usage

What is findDOMNode?

findDOMNode was a method used to search the DOM tree for a specific React component instance. However, it's now deprecated due to potential issues it can cause.

Example of findDOMNode Usage

class OldFinder extends React.Component {
  componentDidMount() {
    const node = ReactDOM.findDOMNode(this);
    node.style.backgroundColor = 'red';
  }

  render() {
    return <div>I'm going to be red!</div>;
  }
}

This code will change the background color of the div to red. However, using findDOMNode like this is discouraged, and Strict Mode will warn you about it.

Modern Alternative

Instead of findDOMNode, you should use refs:

class ModernFinder extends React.Component {
  constructor(props) {
    super(props);
    this.myDiv = React.createRef();
  }

  componentDidMount() {
    this.myDiv.current.style.backgroundColor = 'blue';
  }

  render() {
    return <div ref={this.myDiv}>I'm going to be blue!</div>;
  }
}

This achieves the same result but in a safer, more React-friendly way.

Conclusion

And there you have it, folks! We've journeyed through the land of React's Strict Mode, exploring its warnings about unsafe lifecycles, legacy ref usage, and the deprecated findDOMNode method. Remember, Strict Mode is your friendly neighborhood React developer tool, always there to help you write better, safer code.

As we wrap up, I'm reminded of a student who once told me, "React is like a strict but caring parent – it sets rules to keep us safe, but also gives us the freedom to create amazing things." I couldn't agree more!

Keep practicing, keep learning, and most importantly, keep coding. Until next time, happy React-ing!

Credits: Image by storyset