React Component Defaults

I’m giving up stateless functional components for a while.

They’re super nice but they’re not worth the refactor when you need a lifecycle method.

You could use recompose, which is also super nice, but completely avoidable.

Sticking to Class Components means I won’t need Recompose or a refactor.

If I’m going with Class Components then I might as well go with Pure Class Components.

React.PureComponent stops components from needlessly re-rendering. PureComponent is not something you use on a special occasion, it’s a sensible default.

The only reason I’d need to use a regular class component is when I want the component to re-render when a nested prop or value in state changes.

Then it’s back to React.Component and a shouldComponentUpdate(). A regular component without a shouldComponentUpdate method is now a red flag for me.

I use Pawel’s amazing snippet generator to create my new go-to VS Code snippet:

"Sensible Default Component": {
        "prefix": "rdc",
        "body": [
            "import React, { PureComponent } from 'react';",
            "import PropTypes from 'prop-types';",
            "",
            "class ${1:ComponentName} extends PureComponent {",
            "  static propTypes = {};",
            "",
            "  render() {",
            "    return (",
            "      <div>",
            "          <p>hello</p>",",
            "      </div>",
            "    );",
            "  }",
            "}",
            "",
            "export default ${1:ComponentName};"
        ],
        "description": "React class component with senible defaults"
    }

Another sensible default is using Strict Mode. You can enable <React.StrictMode> in any part of your application and you get a bunch of helpful warnings. Now I wrap my root component in a set of strict mode tags.

Learning Log Stats

 
0
Kudos
 
0
Kudos

Now read this

Rules to Code By

If you’re relatively new to programming: Choose a language and stick to it. Choose a text editor that is easy to learn and stick to it. Avoid large frameworks like Rails and Django until you’ve got a decent grasp on the language you’re... Continue →